Wednesday, July 16, 2014

String.IsNullOrEmpty() vs String.IsNullOrWhiteSpace

String.IsNullOrEmpty() vs String.IsNullOrWhiteSpace

So which would you use?


String.IsNullOrEmpty
String.IsNullOrWhiteSpace
Comments
.NET 2.0 and above
.NET 4 and above

Indicates whether the specified string is null or an Empty string.

Indicates whether a specified string is null, empty, or consists only of white-space characters.






- String.IsNullOrEmpty exists since .NET 2.0 and above
- String.IsNullOrWhiteSpace exists in .NET 4.0 and above


But which should you use?
Here's some useful answer from stackoverflow. 

Example:
string testString = "";
Console.WriteLine(string.Format("IsNullOrEmpty : {0}", string.IsNullOrEmpty(testString)));
Console.WriteLine(string.Format("IsNullOrWhiteSpace : {0}", string.IsNullOrWhiteSpace(testString)));
Console.ReadKey();
Resutl :
IsNullOrEmpty : True
IsNullOrWhiteSpace : True
************************************************************
string testString = " MDS   ";
IsNullOrEmpty : False
IsNullOrWhiteSpace : False
************************************************************
string testString = "   ";
IsNullOrEmpty : False
IsNullOrWhiteSpace : True
************************************************************
string testString = string.Empty;
IsNullOrEmpty : True
IsNullOrWhiteSpace : True
************************************************************
string testString = null;
IsNullOrEmpty : True
IsNullOrWhiteSpace : True

reference: 




happy coding!



No comments :

Post a Comment