Free Information Technology Magazines and eBooks

Tuesday, March 09, 2010

.NET Framework 4.0: Check If String Is Empty or Null Using String.IsNullOrWhiteSpace Method

There is a new class library method in .NET town. You can now easily check whether a specified string is a null reference (Nothing in Visual Basic), empty, or consists only of white-space characters by using String.IsNullOrWhiteSpace Method. This new method is similar to the following code but is far more superior in terms of performance.

VB.NET


Return String.IsNullOrEmpty(value) OrElse value.Trim().Length = 0

C#


return String.IsNullOrEmpty(value) || value.Trim().Length == 0;


Here are sample codes to use the new method:

VB.NET


Module Module1

Sub Main()
Dim samples() As String = {"Fryan", Nothing, String.Empty}
For Each sample As String In samples
Console.WriteLine(String.IsNullOrWhiteSpace(sample))
Next
Console.ReadKey()
End Sub

End Module

C#


class Program
{
static void Main(string[] args)
{
string[] samples = { "fryan", null, String.Empty };
foreach (string sample in samples)
Console.WriteLine(String.IsNullOrWhiteSpace(sample));
Console.ReadKey();
}

}

The above code should display a result of: False, True, True.

To stay up-to-date on Coding Tips & Tricks, subscribe now.

2 comments:

rongchaua said...

Thank you for your introduction but I can not understand where is the difference if I use string.IsNullOrEmpty(). The result gives back False, True, True too.

Anonymous said...

@rongchaua it may give the same result but the performance is a whole lot better!