In C#, IsNullOrWhiteSpace() is a string method. It is used to check whether the specified string is null or contains only white-space characters. A string will be null if it has not been assigned a value or has explicitly been assigned a value of null.
Syntax:
public static bool IsNullOrWhiteSpace(String str)
Explanation: This method will take a parameter which is of type System.String and this method will return a boolean value. If the method’s parameter list is null or String.Empty, or only contains white-space characters then return True otherwise return False.
Example:
Input : str = null // initialize by null value String.IsNullOrWhiteSpace(str) Output: True Input : str = " " // initialize by whitespace String.IsNullOrWhiteSpace(str) Output: True
Program: To demonstrate the working of the IsNullOrWhiteSpace() Method :
// C# program to illustrate // IsNullOrWhiteSpace() Method using System;
class Geeks {
// Main Method
public static void Main( string [] args)
{
string s1 = null ;
// for null value always return true
bool b1 = String.IsNullOrWhiteSpace(s1);
Console.WriteLine(b1);
string s2 = " " ;
// for whitespace value always return true
bool b2 = String.IsNullOrWhiteSpace(s2);
Console.WriteLine(b2);
string s4 = " \n " ;
// for new line value return true
bool b4 = String.IsNullOrWhiteSpace(s4);
Console.WriteLine(b4);
string s5 = "\t" ;
// for tab value return true
bool b5 = String.IsNullOrWhiteSpace(s5);
Console.WriteLine(b5);
string s6 = "\r" ;
// for carriage Return value return true
bool b6 = String.IsNullOrWhiteSpace(s6);
Console.WriteLine(b6);
string s7 = "GFG" ;
// for s7 it return False
bool b7 = String.IsNullOrWhiteSpace(s7);
Console.WriteLine(b7);
}
} |
True True True True True False
Note: There is a alternative code of IsNullOrWhiteSpace() method as follows:
return String.IsNullOrEmpty(str) || str.Trim().Length == 0;
Program: To demonstrate IsNullOrEmpty() method’s alternative
// C# program to illustrate the // similar code for IsNullOrWhiteSpace() using System;
class Geeks {
// similar code to
// IsNullOrWhiteSpace()
public static bool check( string str)
{
return (String.IsNullOrEmpty(str) ||
str.Trim().Length == 0) ? true : false ;
}
// Main Method
public static void Main( string [] args)
{
string s1 = "GeeksforGeeks" ;
string s2 = " " ;
string s3 = null ;
string s4 = " \n " ;
bool b1 = check(s1);
bool b2 = check(s2);
bool b3 = check(s3);
bool b4 = check(s4);
// To display result
Console.WriteLine(b1);
Console.WriteLine(b2);
Console.WriteLine(b3);
Console.WriteLine(b4);
}
} |
False True True True
Reference: https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace