String extension methods

I got really tired of the IsNullOrEmpty static method, so I converted it into an extension method:

public static class StringExtensions
    public static bool IsNullOrEmpty(this string value)
        return string.IsNullOrEmpty(value);

Since that method was already static, I just put a simple wrapper around it.  All scenarios pass:

public void Matches_existing_behavior()

    string value = null;


    value = string.Empty;


    value = "blarg";


The only rather strange thing about extension methods is that they can be called by null references, as shown in the test above.  As long as everyone understands that extension methods are syntactic sugar and not actually extending the underlying types, I think it’s clear enough.

The extension method is more readable and lets me work with strings instead of having to remember that it’s a static method.  Static methods that reveal information about instances of the same type seem to be prime candidates for extension methods.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in C#. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • I havent started playing with extension methods yet but I will definately find a use for them.

    Funny literals you have in your example. Were you making a pirate application? =)