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:

[TestMethod]
public void Matches_existing_behavior()
{
    Assert.IsFalse("blarg".IsNullOrEmpty());
    Assert.IsTrue(((string)null).IsNullOrEmpty());
    Assert.IsTrue("".IsNullOrEmpty());

    string value = null;

    Assert.IsTrue(value.IsNullOrEmpty());

    value = string.Empty;

    Assert.IsTrue(value.IsNullOrEmpty());

    value = "blarg";

    Assert.IsFalse(value.IsNullOrEmpty());
}

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.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

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.
  • http://www.lostechies.com/blogs/sean_chambers Sean Chambers

    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? =)

    blarg!