In this post we will discuss C# | IsNullOrWhiteSpace() Method. It is used with String class and helpful to check null and whitespaces. This method is similar to string.IsNullOrEmpty() but it does not check for white spaces in given string. This method returns true if the entered string has null or whitespace characters in it.
In below code both will return true because it contains null and in second one it contains whitespace characters.
bool val1 = string.IsNullOrWhiteSpace(null); // it will return True
bool val2 = string.IsNullOrWhiteSpace(" "); //it will return True
Example of IsNullOrWhiteSpace() Method:
class CodeConfig
{
static void Main(string[] args)
{
bool val1 = string.IsNullOrWhiteSpace(null);
bool val2 = string.IsNullOrWhiteSpace(" ");
bool val3 = string.IsNullOrWhiteSpace("5");
// below will return false bacause it does not handle white space chars but above does.
bool val4 = string.IsNullOrEmpty(" ");
Console.WriteLine(val1);
Console.WriteLine(val2);
Console.WriteLine(val3);
Console.WriteLine(val4);//it is output of IsNullOrEmpty.(Highlighted in yellow below)
Console.ReadLine();
}
}
Output:
You can check more detail of IsNullOrEmpty() or can read out our Interview Section.