Wednesday, March 11, 2009

IsEmpty and IsNull Extension Methods on the String Class

There have been a few times I've wanted a string.IsEmpty() method that would only return true if the string was actually empty. That's an extraordinarily uncommon situation, but more common than that would be a string.IsNull() that returns false if you pass it string.Empty.

The problem is, of course, if you're going to add extension methods for IsEmpty and IsNull, you really ought to go ahead and add one for IsNullOrEmpty so you can keep all of your method calls looking the same.

Here's a set of extension methods I wrote for helping out with dealing with null or empty strings:
public static bool IsEmpty(this string s)
{
return (s != null && s.Length == 0);
}

public static bool IsNull(this string s)
{
return (s == null);
}

public static bool IsNullOrEmpty(this string s)
{
return string.IsNullOrEmpty(s);
}

No comments:

Post a Comment