Monday, November 26, 2007

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.

No comments: