Friday 11 June 2010

A Useful New String Method in .NET 4.0

In .NET 2.0 the String class introduced a method, IsNullOrEmpty, that allows you to check whether a string is null or the Empty string. However, sometimes you also want to disallow a string that contains just white space. I created a static utility method called IsNullOrEmptyOrBlank that additionally checked for white space.

public static bool IsNullOrEmptyOrBlank(string s)
{
return String.IsNullOrEmpty(s) || s.Trim().Length == 0;
}



In .NET 3.5 I turned this into an extension method.



public static bool IsNullOrEmptyOrBlank(this string s)
{
return String.IsNullOrEmpty(s) || s.Trim().Length == 0;
}



Then to my pleasure I noticed that in .NET 4.0 Microsoft has fixed this oversight and added this functionality to the String class.  The method is IsNullOrWhiteSpace. The description is: “Indicates whether a specified string is null, empty, or consists only of white-space characters.”



Kudos to Microsoft.  :-)

No comments:

Post a Comment