Checking For Empty or Null String in C#

(The source code is attached.)

In this article we will look at how to simplify checking for NULL and empty strings using C#. Most of you might have come across a requirement of checking whether a given string is null or empty. Let's have a look at the code:

One usual way to code is to do as follows:

static void Main(string[] args)

{

    string testString = "";

    bool hasValue;

    if (testString == null || testString == "")

        hasValue = false;

    else

        hasValue = true;

}

Let's simplify this code by using the static method of the String class. The method name is IsNullOrEmpty. The following is the code:

IsNullOREmptyWithOutSpace

Now if you run this application, you will get hasValue = false, that is correct and as expected. Let's modify the string variable by assigning it a space as shown in the following code:

IsNullOREmptyWithSpace

Now if you run the code above, you will get hasValue = true. Although your testString has nothing except one space, the IsNullOrEmpty method is still giving us true.

IsWhiteSPace

REASON: Because the IsNullOrEmpty method doesn't treat white spaces as empty.

RESOLUTION: To resolve the preceding sort of issues another static method is available on the String class and named IsNullOrWhiteSpace. Let's have a look at the code.

Now, if you will run the code, it will provide you the correct result as expected with hasValue=false.