Loading ...

string.IsNullOrWhiteSpace() Method in .NET 4.0 | CodeAsp.Net

string.IsNullOrWhiteSpace() Method in .NET 4.0

 /5
0 (0votes)

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 : True
resultTwo : False
resultThree : 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 : True
resultTwo : True
resultThree : True

So you can see that IsNullOrWhiteSpace method is a nice addition in .NET Framework 4.0.

Comments (no comments yet)

Top Posts