Sunday, 18 December 2011

String.IsNullOrEmptyWhiteSpace Extension Method

This is hopefully the first of a series of related posts on some useful Extension methods that I've written. If you're not familiar with Extension methods then think of them as additional methods that you can add to any class you want additional functionality or behaviour for. For example, you can add a new method to the .NET BCL String class (as in this post). Prior to this feature, you could achieve this by deriving from a class and adding a new method in the deriving class, but Extension methods now give you a more reusable alternative. I'd recommend reading up on this topic by clicking here.

One thing I often find myself having to do is validate a string for not being empty. One fairly primitive way to accomplish this is to test for the following condition in an if statement:

input.Equals(string.Empty)
This will return true if input is an empty string. Sometimes, however, you need to also test if the input contains empty white space. Imagine if the user accidently hit the space key and the value for input was the string "  ". The test above would return false in such a case. To cater for such scenarios, I wrote the following extension method in a class library project.

public static bool IsNullOrEmptyWhiteSpace(this string str)
{
     return (str == null || str.Trim().Equals(string.Empty));
}
The test would now look like:

if (input.IsNullOrEmptyWhiteSpace())
     //Tell user to enter something
** Update (13/03/2013) **

As of .NET 4 the static method IsNullOrWhiteSpace was added to the String datatype, therefore making the extension method above redundant (unless you're still using earlier versions of the framework :).

No comments:

Post a Comment