An extension method, just because I can.

Going to the dentist is an awkward experience. You know you have to use their service or your teeth will rot, but the experience is just not enjoyable.

That's how I feel about string.Format. I use it all over the place, but find it incredibly out of place. Thanks to extension methods though, I can propose a nicer syntax. Here's a snippet from a site I'm building for one of my clients, using my rasta REST framework and linq2sql.

[HttpOperation(HttpMethod.GET, ContentType=new HttpContentType("image/*"))]

public ResourceOperationResult GetMovie(string filmName)

{

    var movie = _movies.FindOne(movie => movie.UrlTitle == filmName);

 

    if (movie == null)

        throw new ResourceNotFoundException

        {

            Message = "The movie {0} wasn't found in the database.".With(filmName)

        };

 

    return new ResourceMovedTemporarilyResult { NewResourceUrl="/library/tempfilm.jpg" };

}

Notice the extension method there? I just find it sweet. Here's the very simple extension method.

public static string With(this string text, params object[] values)

{

    return string.Format(text, values);

}

There you are, a shamefully simple extension method, just because I can!

Ads

Comment