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


Leave a Reply

Your email address will not be published. Required fields are marked *