Checking for Empty Strings

Posted Sat, Aug 14 2010 21:46 by Deborah Kurata

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!

Filed under: , , ,

Comments

# re: Checking for Empty Strings

Thursday, August 19, 2010 11:27 AM by Bob Bingham

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.

# re: Checking for Empty Strings

Wednesday, August 25, 2010 5:19 PM by Joacim Andersson

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.

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: