.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.

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.

publicstaticclassStringHelper

{

publicstaticbool IsNullOrWhiteSpace(string s)

{

if (s == null)

returntrue;

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.

8 Comments

Great~
But this method name is too long.
Maybe IsNullOrSpace is enought ^_^

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.

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.