Most of the times we use string.IsNullOrEmpty and sometimes string.IsNullOrWhiteSpace. The method names itself are self explanatory but to understand them better we will see an example.
String.IsNullOrEmpty:
Function used to check whether string is null or empty.
String.IsNullOrEmpty = (Variable == null || Variable == string.Empty)
String.IsNullOrWhiteSpace:
Function used to check whether a string is null, or contains only of white-space characters, or string.Empty
String.IsNullOrWhiteSpace = (string.IsNullOrEmpty(Variable) || Variable.Trim().Length == 0)
Example:
namespace DotNetMirror
{
class StringIsNullOrWhiteSpaceAndStringIsNullOrEmpty
{
static void Main(string[] args)
{
string strVar1 = null;
string strVar2 = " ";
string strVar3 = " dnm ";
string strVar4 = "";
string strVar5 = "dotnetmirror";
#region IsNullOrWhiteSpace
Console.WriteLine("IsNullOrWhiteSpace method");
Console.WriteLine("String strVar1 {0}", CheckIsNullOrWhiteSpace(strVar1));
Console.WriteLine("String strVar2 {0}", CheckIsNullOrWhiteSpace(strVar2));
Console.WriteLine("String strVar3 {0}", CheckIsNullOrWhiteSpace(strVar3));
Console.WriteLine("String strVar4 {0}", CheckIsNullOrWhiteSpace(strVar4));
Console.WriteLine("String strVar5 {0}", CheckIsNullOrWhiteSpace(strVar5));
#endregion
#region IsNullOrEmpty
Console.WriteLine("IsNullOrEmpty method");
Console.WriteLine("String strVar1 {0}", CheckIsNullOrEmpty(strVar1));
Console.WriteLine("String strVar2 {0}", CheckIsNullOrEmpty(strVar2));
Console.WriteLine("String strVar3 {0}", CheckIsNullOrEmpty(strVar3));
Console.WriteLine("String strVar4 {0}", CheckIsNullOrEmpty(strVar4));
Console.WriteLine("String strVar5 {0}", CheckIsNullOrEmpty(strVar5));
#endregion
Console.ReadLine();
}
public static string CheckIsNullOrWhiteSpace(string str)
{
if (string.IsNullOrWhiteSpace(str))
return string.Format("[{0}] is Null or Empty or White-space.", str);
else
return string.Format("[{0}] is NOT Null or Empty or White-space.", str);
}
public static string CheckIsNullOrEmpty(string str)
{
if (string.IsNullOrEmpty(str))
return string.Format("[{0}] is Null or Empty.", str);
else
return string.Format("[{0}] is NOT Null or Empty.", str);
}
}
}
Output: