C# string.IsNullOrWhiteSpace

String type

The string.IsNullOrWhiteSpace method tests an entire string. It returns true if the string contains only whitespace characters or is null. This method provides a declarative and effective way of making this determination.

Null

Example

Newline

Please remember that whitespace characters in C# programs can be encoded as \n for new lines, \r for carriage returns, or even \v for vertical spaces. Not only this, but whitespaces can include regular spaces and tab characters \t.

Whitespace

Note:IsNullOrWhiteSpace handles all these cases. It scans the entire input string if the string has more than one whitespace character.

Tip:The string must be entirely whitespace chars or null for the result to be true.

C# program that uses IsNullOrWhiteSpace

using System;

class Program
{
    static void Main()
    {
	bool a = string.IsNullOrWhiteSpace("   ");
	bool b = string.IsNullOrWhiteSpace("\n");
	bool c = string.IsNullOrWhiteSpace("\r\n\v ");
	bool d = string.IsNullOrWhiteSpace(null);
	bool e = string.IsNullOrWhiteSpace("");
	bool f = string.IsNullOrWhiteSpace(string.Empty);
	bool g = string.IsNullOrWhiteSpace("dotnetperls");
	Console.WriteLine(a);
	Console.WriteLine(b);
	Console.WriteLine(c);
	Console.WriteLine(d);
	Console.WriteLine(e);
	Console.WriteLine(f);
	Console.WriteLine(g);
    }
}

Output

True
True
True
True
True
True
False
Note

We see that all the arguments to the IsNullWhiteSpace method result in a true value except the value. The final method call, which passes the argument "dotnetperls", generates the false value.

Thus:Whatever "dotnetperls" may be, it is not considered null or whitespace by the .NET Framework.

Internals

Framework: NET

How is the IsNullOrWhiteSpace method implemented in the .NET Framework 4.0? The method first branches on the null comparison to the string variable. Next, if non-null, it scans the individual characters and invokes the IsWhiteSpace method.

Also:The IsNullOrWhiteSpace method returns early if it finds a non-whitespace character.

Implementation in .NET Framework: C#

public static bool IsNullOrWhiteSpace(string value)
{
    if (value != null)
    {
	for (int i = 0; i < value.Length; i++)
	{
	    if (!char.IsWhiteSpace(value[i]))
	    {
		return false;
	    }
	}
    }
    return true;
}
Performance optimization

For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data.

Tip:As always, premature optimization may be evil, but it is also fun. It can help teach us more about the programming language.

Summary

The string.IsNullOrWhiteSpace method provides a handy and efficient way to determine some information about a string in your program. This article demonstrated the kinds of arguments that will yield a true or false result.


C#: String