posted 6/7/2010 by Samir NIGAM
As we know that, the method IsNullOrEmpty don’t work on white spaces. e.g. consider the following code snippet –
string inputOne = string.Empty; string inputTwo = " "; string inputThree = "\t\r\n\n"; bool resultOne = string.IsNullOrEmpty(inputOne); bool resultTwo = string.IsNullOrEmpty(inputTwo); bool resultThree = string.IsNullOrEmpty(inputThree); Response.Write(string.Format("resultOne : {0}", resultOne)); Response.Write(string.Format("resultTwo : {0}", resultTwo)); Response.Write(string.Format("resultThree : {0}", resultThree));
On executing the above code snippet, we find output as-
resultOne : TrueresultTwo : FalseresultThree : False
Note that although the inputTwo string is empty, but method IsNullOrEmpty is not able to detect it.
To overcome this issue, .NET Framework 4.0 introduces a new static method on string class called IsNullOrWhiteSpace to work on white spaces.
Lets re execute the above code snippet for IsNullOrWhiteSpace method as-
string inputOne = string.Empty; string inputTwo = " "; string inputThree = "\t\r\n\n"; bool resultOne = string. IsNullOrWhiteSpace (inputOne); bool resultTwo = string. IsNullOrWhiteSpace (inputTwo); bool resultThree = string. IsNullOrWhiteSpace (inputThree); Response.Write(string.Format("resultOne : {0}", resultOne)); Response.Write(string.Format("resultTwo : {0}", resultTwo)); Response.Write(string.Format("resultThree : {0}", resultThree));
And we find output as-
resultOne : TrueresultTwo : TrueresultThree : True
So you can see that IsNullOrWhiteSpace method is a nice addition in .NET Framework 4.0.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18