If you have been spending anytime developing for the .NET Framework 4 in Visual Studio 2010, you may have noticed a new static method on the string class, called IsNullOrWhiteSpace, in addition to the more familiar IsNullOrEmpty method.
In many instances String.IsNullOrEmpty() really wasn’t that helpful as it didn’t return true if the string only included whitespace characters ( characters that were not visible on the screen ). In most instances a string full of whitespace characters can be considered an empty string.
To help with this situation, .NET Framework 4 has included a String.IsNullOrWhiteSpace() method that will return true if a string is full of whitespace characters. Let’s take the example below where there is an input string with a space, carriage return, linefeed and tab.
Calling String.IsNullOrEmpty(input) on that string will return false as the string is not null and it is not empty. However, calling String.IsNullOrWhiteSpace(input) will return true as the string is indeed full of whitespace characters.
class Program
{
static void Main(string[] args)
{
string input = " \r\n\t";
if (string.IsNullOrEmpty(input))
Console.WriteLine("This won't display.");
if (string.IsNullOrWhiteSpace(input))
Console.WriteLine("This will display");
Console.ReadLine();
}
}
The String.IsNullOrWhiteSpace() Method is a nice addition to .NET Framework 4 which you can use in Visual Studio 2010.

Comments