Helper Methods: How to Determine if a String is Empty, Null, or WhiteSpace

C# has two very under appreciated helper methods that can be used to quickly determine whether a string is null, empty, or just contains whitespace.

To determine whether a string is empty (Length == 0) or null, you can use the static string helper method string.IsNullOrEmpty(). Using this helper method to determine if a string is null or just empty is the difference between:

if (thisString == null || thisString == 0)
{
// code to execute
}

And:

if (string.IsNullOrEmpty(thisString))
{
//code to execute
}

The second example which takes advantage of the helper method is much more concise.

To find out of a string is null or just contents white space, you can use a similar method: string.IsNullOrWhiteSpace(), which can pretty much be used in the same way as string.IsNullOrEmpty. An example of when you might find this method useful is if you wanted to check a bunch of text strings to make sure they don’t have any spaces occurring before or after (because perhaps you’re going to concatenate the strings and want to avoid double spaces between words). Instead of using .Trim() to generate a new string and remove the whitespace, you can use .IsNullOrWhiteSpace to identify the whitespace without having to create a new string, which is a big time saver and makes for more efficient code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download