C# | IsNullOrWhiteSpace() Method
Last Updated :
31 Jan, 2019
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 :
using System;
class Geeks {
public static void Main( string [] args)
{
string s1 = null ;
bool b1 = String.IsNullOrWhiteSpace(s1);
Console.WriteLine(b1);
string s2 = " " ;
bool b2 = String.IsNullOrWhiteSpace(s2);
Console.WriteLine(b2);
string s4 = " \n " ;
bool b4 = String.IsNullOrWhiteSpace(s4);
Console.WriteLine(b4);
string s5 = "\t" ;
bool b5 = String.IsNullOrWhiteSpace(s5);
Console.WriteLine(b5);
string s6 = "\r" ;
bool b6 = String.IsNullOrWhiteSpace(s6);
Console.WriteLine(b6);
string s7 = "GFG" ;
bool b7 = String.IsNullOrWhiteSpace(s7);
Console.WriteLine(b7);
}
}
|
Output:
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
using System;
class Geeks {
public static bool check( string str)
{
return (String.IsNullOrEmpty(str) ||
str.Trim().Length == 0) ? true : false ;
}
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);
Console.WriteLine(b1);
Console.WriteLine(b2);
Console.WriteLine(b3);
Console.WriteLine(b4);
}
}
|
Output:
False
True
True
True
Reference: https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace
Share your thoughts in the comments
Please Login to comment...