BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 4.0+

String.IsNullOrWhiteSpace

When working with user input it is common to check that a string has been provided. With the .NET framework version 4.0, a single method can be used to determine whether such a string is null, empty or contains only white space characters.

Checking for Empty Strings

When using the .NET framework version 3.5 or some earlier versions, you can check if a string is either empty or contains null using the static method, IsNullOrEmpty. This returns a Boolean value of true if the string is null or empty and false otherwise, as shown below:

bool result;
result = string.IsNullOrEmpty(null);        // true
result = string.IsNullOrEmpty("");          // true
result = string.IsNullOrEmpty(" ");         // false
result = string.IsNullOrEmpty("Test");      // false

When checking that a user has provided valid input you will often want to ensure that a string is null, empty or contains only white space characters. This prevents the user from entering only a space when a response is required. Before the .NET framework version 4.0, you would do this by first checking if the string was null. If not null, you would trim the white space from the value and check if the result was empty, usually by reading the Length property.

The following code shows this with calls to a method named, "IsNullOrWhiteSpace", which performs the two checks.

static void Main()
{
    bool result;
    result = IsNullOrWhiteSpace(null);      // true
    result = IsNullOrWhiteSpace("");        // true
    result = IsNullOrWhiteSpace(" ");       // true
    result = IsNullOrWhiteSpace("\t");      // true
    result = IsNullOrWhiteSpace("Test");    // false
}

static bool IsNullOrWhiteSpace(string value)
{
    return value == null || value.Trim().Length == 0;
}

.NET 4.0 includes such a method within the String class. It is a static method that accepts a single parameter containing the string to be tested. We can therefore recreate the above example using the standard method, as follows:

bool result;
result = string.IsNullOrWhiteSpace(null);   // true
result = string.IsNullOrWhiteSpace("");     // true
result = string.IsNullOrWhiteSpace(" ");    // true
result = string.IsNullOrWhiteSpace("\t");   // true
result = string.IsNullOrWhiteSpace("Test"); // false

When checking for white space, the method uses the rules defined in the Unicode character set. White space includes spaces, tabs, carriage returns and many other non-printing character codes. You can check if any individual character is classed as white space using the char.IsWhiteSpace method.

27 August 2011