Extension Methods

Starting in .NET 3.5, a new feature was added called Extension Methods. Microsoft defines them as:

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

I really like them and use them as much as possible. There tons of them in my open-source assembly located at: http://dotnettips.codeplex.com/

A good candidate for an Extension method is code you do against a type over and over again. Case in point:

var dt = QuerySpecificDB(databaseName, storedProcedure, parameters);
if (dt != null && dt.Rows.Count > 0)
{
  // Code removed for brevity
}

I have seen the code above repeated over and over again in our code to verify that the DataTable has data in it. With and Extension method you simply need to do this instead:

var dt = QuerySpecificDB(databaseName, storedProcedure, parameters);
if (dt.HasRows())
{
  // Code removed for brevity
}

As you can see in this code, it’s much easier, more readable and repeatable. To use the Extensions method just add this namespace to the top of the class.

Here is the complete code for the Extension class:

/// <summary>
/// Extensions for <see cref="DataTable"/>
/// </summary>
public static class DataTableExtensions
{
   /// <summary>
   /// Determines whether the specified <see cref="DataTable"/> has rows.
   /// </summary>
   /// <param>The table.</param>
   /// <returns>
   ///    <c>true</c> if the specified table has rows; otherwise, <c>false</c>.
   /// </returns>
   public static bool HasRows(this DataTable dt)
   {
      return ((dt != null) && (dt.Rows != null) && (dt.Rows.Count > 0));
   }
}

Tip By: David McCarter

One thought on “Extension Methods

  1. I find it handy when going from the UI layer to the data layer. Your textbox might be empty, so when you update the data, you want to be null.

    public static string NullIfEmpty(this TextBox textBox)
    {
    if (textBox != null)
    {
    if (string.IsNullOrWhiteSpace(textBox.Text))
    return null;
    else
    return textBox.Text;
    }
    else
    throw new ArgumentNullException(…);
    \\or return null;
    }
    }

    public static string EmptyIfNull(this string value)
    {
    if (string.IsNullOrWhiteSpace(value))
    return string.Empty;
    else
    return value;
    }

    MyTable.MyField = myTextBox.NullIfEmpty();

    myTextBox.Text = MyTable.MyField.EmptyIfNull();

    Purists might not like it, but remembering that the Extension method is still a static method inspite of its use syntax it can be handy to wrap static methods to make them seem more non-static. Like in the case of the first, I needn’t check whether my TextBox type parameter is null before I “dereference” the NullIfEmpty method because it’s a static method and I added that check inside the method.

Comments are closed.