Select Page

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 C# 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 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 the 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 C# 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 the more efficient code.

Share This