Posts tagged ‘IsNullOrEmpty’

C#: Does the String Have Content – My Newest Favorite Extension Method

Everyone knows that one should do two things before using a string in C#. One is to check to see if it is null and the other is to check to see if it actually has content, not just blank. The primary way of doing that is to use the static method on the stringIsNullOrEmpty such as

string txt;

if (string.IsNullOrEmpty( txt ) == false)
{
   // Valid string do something
}

I have religiously been using that string checking paradigm (see my 2007 rants on it here (Is String.IsNullOrEmpty Hazardous to your Code’s health in .Net 2.0/3.0?)) for awhile now.

Issues

But I had two issues with using string.IsNullOrEmpty:

  1. The negative result of the method call (false) is telling me that the string is OK to use. Every so often I would call it without checking for that false condition. Grrr! I only want to do actions on it if it valid, not invalid.
  2. My way of working/thinking is that I type in the string name first and then think of testing it. Visual Studio’s Intellisense doesn’t help me, for I have already typed in the variable. I have to go back and add string.IsNullOrEmpty.

Solution

With the advent of extension methods I can solve both issues by making an extension method of what I want. By giving it a name which suggests a positive result means that the string is viable, I solve #1. By making it an extension method, I solve #2 above because it now shows up in Intellisense! Here is the code written as an extension

/// <summary>
/// Does the string contains text? Same as (IsNullOrEmpty() == false).
/// </summary>
/// <param name="txt">Text to look at.</param>
/// <returns>True if valid and contains text.</returns>
public static bool ContainsText( this string txt )
{
    return string.IsNullOrEmpty( txt ) == false;
}

Because I name it with a C, it shows up in the first set of selections in intellisense. That is a bonus.

Note this works even if the string is null! Give it a try!

Share