Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

August 14, 2010

Checking for Empty Strings

Filed under: C#,VB.NET @ 11:46 pm

The "old school" way to check for empty strings is to use the Trim function to remove any empty spaces and then either check for a length of 0 or a string value of "".

In C#:

var str = "";
if (str.Trim().Length == 0)
{
    MessageBox.Show("Please enter a value");
}

In VB:

Dim str As String = ""
If (str.Trim().Length = 0) Then
    MessageBox.Show("Please enter a value")
End If

But if the string str is Null, the check above throws an exception. So to cover all of the bases, you need a null check as well.

A much easier way is to use the IsNullOrEmpty function, or new with .NET 4.0, the IsNullOrWhiteSpace.

In C#:

var str = "";
if (String.IsNullOrWhiteSpace(str))
{
    MessageBox.Show("Please enter a value");
}

In VB:

Dim str As String = ""
If (String.IsNullOrWhiteSpace(str)) Then
    MessageBox.Show("Please enter a value")
End If

Use this technique any time you want to check whether a string has no value.

Enjoy!

2 Comments

  1.   Bob Bingham — August 19, 2010 @ 11:27 am    Reply

    The even older way to do it in VB is:

    Dim str as string = “”
    If Trim(str) = “” Then
    ‘Complain
    End if

    It works fine if the string is Nothing and, IMHO, is easier to read.

  2.   Joacim — August 25, 2010 @ 5:19 pm    Reply

    It’s funny, but long before beta 1 of VS2010 when I first discovered that MS had added the IsNullOrEmptyWhitespace static method to the String class, the first extension method I ever wrote in VS2008 was IsNullOrEmptyWhitespace.

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2020 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs