Check whether a string is null, empty, or only contains the white-space characters

If you are working with the .Net framework 4.5, you can use the String.IsNullOrWhiteSpace Method to specify the string is null, empty, or consists only of white-space characters.

The following example contains the five string type variables, we pass the each variable into the IsNullOrWhiteSpace method to check whether a string is null, empty, or only contains the white-space characters.

string str1 = null;
string str2 = "author";
string str3 = "   \t ";
string str4 = String.Empty;
string str5 = " ";
 
Console.WriteLine(String.IsNullOrWhiteSpace(str1));
Console.WriteLine(String.IsNullOrWhiteSpace(str2));
Console.WriteLine(String.IsNullOrWhiteSpace(str3));
Console.WriteLine(String.IsNullOrWhiteSpace(str4));
Console.WriteLine(String.IsNullOrWhiteSpace(str5));
 
 
// The output will be:
// True
// False
// True
// True
// True

If the string is the null, empty or contains only the white spaces then the method will return the True Boolean value otherwise the method will return the False value.

There is other method String.IsNullOrEmpty that indicates whether the specified string is null or an Empty string.

Author: Hirendra Sisodiya

Programmer at PSPL. Can be found on Google Plus.