Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

.Net Framework 4.0: string.IsNullOrWhiteSpace() method

.Net Framework 4.0 Beta 2 has new IsNullOrWhiteSpace() method for strings generalizes IsNullOrEmpty() method to incluse also other white space besides empty string. In this posting I will show you simple example that illustrates how to use IsNullOrWhiteSpace() method.

Term “white space” includes all characters that are not visible on screen. By example, space, line break, tab and empty string are white space characters. The following example shows how to use IsNullOrWhiteSpace() method.


static void Main(string[] args)

{

    string helloString = "Hello, world!";

    string nullString = null;

    string emptyString = string.Empty;

    string whiteSpaceString = "\t\r\n ";

 

    Console.WriteLine("Is null or whitespace?");

    Console.WriteLine("-----------------------");

    Console.WriteLine("helloString: " + string.IsNullOrWhiteSpace(helloString));

    Console.WriteLine("nullString: " + string.IsNullOrWhiteSpace(nullString));

    Console.WriteLine("emptyString: " + string.IsNullOrWhiteSpace(emptyString));

    Console.WriteLine("whiteSpaceString: " + string.IsNullOrWhiteSpace(whiteSpaceString));

 

    Console.ReadLine();

}


When you run this example you get the following output.


Is null or whitespace? ----------------------- helloString: False nullString: True emptyString: True whiteSpaceString: True

IsNullOrWhiteSpace() is useful in scenarios where string to be checked may contain some white space characters instead of null or empty string. You can use this method to check values that user inserts to form fields, by example.

Also you can use this method with fixed-length character fields in database. These fields left-pad their values with spaces to field length and if database provider doesn’t trim values of these fields automatically you can use IsNullOrWhiteSpace() methods to check if field has value or not.

IsNullOrWhiteSpace() for older .Net Framework versions

If you like IsNullOrWhiteSpace() method but you cannot move to .Net Framework 4.0 you can use helper class with IsNullOrWhiteSpace() method. Yes, you have to use some helper class because you cannot add static extension methods to existing classes without recompiling them.


public static class StringHelper

{

    public static bool IsNullOrWhiteSpace(string s)

    {

        if (s == null)

            return true;

 

        return (s.Trim() == string.Empty);

    }

}


Well, that’s it. If you have some interesting uses for IsNullOrWhiteSpace() method then feel free to drop a comment here.


kick it on DotNetKicks.com pimp it 顶 Progg it Shout it
Shout it!
Posted: Oct 25 2009, 11:14 AM by DigiMortal | with 23 comment(s)
Filed under: ,

Comments

silvernight said:

Great~

But this method name is too long.

Maybe IsNullOrSpace is enought ^_^

# October 25, 2009 2:10 PM

quachnguyen said:

     public static bool IsNullOrWhiteSpace(string s)

       {

           if (s==null || "".Equals(s.Trim()))

           {

               return (true);

           }

           return (false);

       }

Very helpful new method

# October 25, 2009 10:06 PM

JMA said:

Hi, Gunnar.

Maybe you forgot the keyword "this"?

...

public static bool IsNullOrWhiteSpace(this string s)

...

Good post!

JMA

# October 26, 2009 6:49 AM

new292 said:

Thanks :)

# October 26, 2009 8:18 AM

RichardD said:

With a little LINQ, you can make this much more efficient:

public static bool IsNullOrWhiteSpace(this string s)

{

   if (string.IsNullOrEmpty(s)) return true;

   return s.All(char.IsWhiteSpace);

}

This avoids creating a new string, and will stop testing at the first non-whitespace character.

Without LINQ, it's not quite as neat:

public static bool IsNullOrWhiteSpace(this string s)

{

   if (!string.IsNullOrEmpty(s))

   {

       foreach (char c in s)

       {

           if (!char.IsWhiteSpace(c))

           {

               return false;

           }

       }

   }

   return true;

}

# October 26, 2009 2:28 PM

Amr Badawy said:

public static bool IsNullOrWhiteSpace(string s)

{

   return (s==null || "".Equals(s.Trim()));

}

# October 27, 2009 6:25 AM

Visual C# Kicks said:

Is this replacing IsNullOrEmpty?

# October 29, 2009 7:19 PM

Someone said:

Does anyone know why the null terminator char \0 isn't handled by this new method?  \0 can be embedded in strings and as far as I know it is not normally visible on the screen unless using an app like Notepad++ with the "show all characters" option enabled.

string test = "   \0   ";

string.IsNullOrWhiteSpace(test) // returns false

I guess I'll just stick to my extension method:

private static bool IsNull(this string s)

{

 if (s == null || s.Length == 0)

   return true;

 char c;

 for (int i = 0; i < s.Length; i++)

 {

   c = s[i];

   if (!char.IsWhiteSpace(c) && c != '\0')

     return false;

 }

 return true;

}

IsNull(null) // returns true

IsNull("  ") // returns true

IsNull("  \0  ") // returns true

IsNull("abc") // returns false

IsNull(" a b c") // return false

IsNull(" \t ") // return true

I didn't have to check for the \0 char until I started getting files from users where \0 was embedded randomly throughout text files causing unwanted results due to the null check failing.  It was hard to debug the issue at first since \0 looks like a normal whitespace when using the text visualizer inside Visual Studio.  It wasn't until I used Notepad++ with "Show All Characters" that I was able to find \0 char in the files.

# November 9, 2009 1:34 AM