Helpful Extension Method: IsBlank

2013-09-20 9:53 PM

I frequently find myself using the static string methods like Format() and IsNullOrWhitespace(). Due to my laziness and the perceived inelegance of calling those static methods every time I want to use them, I have developed some helpful wrappers over time.

IsBlank

public static bool IsBlank(this string input)
{
    return string.IsNullOrWhitespace(input);
}

The really nice thing about this one is that it works on objects that are null due to the nature of extension methods. It allows your code to be more readable since the reader's comprehension doesn't have to dart around.

if(string.IsNullOrWhitespace(getAString()))

dances around the usual flow of thought: rather than saying "is this string blank," you're asking "is null or whitespace this string?" If you're a fan of Yoda conditions this may be intuitive, but I perceive this to be much more easily comprehensible:

if(getAString().IsBlank())

IsNotBlank

public static bool IsNotBlank(this string input)
{
    return !input.IsBlank()
}

Since one of the goals of IsBlank() is immediate readablilty, it makes sense to have another method which is just a thin logical NOT wrapper. In my mind, it's much easier to miss the bang in !input.IsBlank() than it is to miss the intent of input.IsNotBlank().