Check if string is empty or all spaces in C#

Cody picture Cody · Sep 16, 2011 · Viewed 57.3k times · Source

How to easily check if a string is blank or full of an undetermined amount of spaces, or not?

Answer

Merlyn Morgan-Graham picture Merlyn Morgan-Graham · Sep 16, 2011

If you have .NET 4, use the string.IsNullOrWhiteSpace method:

if(string.IsNullOrWhiteSpace(myStringValue))
{
    // ...
}

If you don't have .NET 4, and you can stand to trim your strings, you could trim it first, then check if it is empty.

Otherwise, you could look into implementing it yourself:

.Net 3.5 Implementation of String.IsNullOrWhitespace with Code Contracts