Extension Methods

Extension methods are really cool.  The following is an example of one, and I'll discuss it in detail:

public static class StringExtensions
{
   public static string GetFormattedValue(this string data)
   {
      //Do some formatting
   }
}

In the above example, you notice similarities to a normal static class; however, this can be applied to an instance of a string, as shown below:

string value = "   this is my sentence.   ";
string formattedText = value.GetFormattedValue();

The method defined in the static method above can be used in the string instance below.  Let's go into detail.  An extension class in this situation must be a static class; that is a requirement.  Secondly, the "this" declaration as the first parameter notes the type to extend (a string in this instance).  It, in reality, can be any instance class in the .NET framework or any custom library (no limitations except for non-static classes only).  Next, the first parameter of this static extension method is the type to extend, but the rest of the parameters are the parameters for the method.  So if the method was:

public static string GetFormattedValue(this string data, bool trim, bool punctuate, bool camelCase)
{
   //Do some formatting
}

It would be invoked as such:

string formattedText = value.GetFormattedValue(true, false, false);

Very handy to have.  And very easy to create.  You will see this a lot in the .NET framework 3.5; the lambda expression methods (Where, Contains, First, etc.) are often static extensions defined on the list, and there are many other places throughout.

Comments

# LINQ to SQL and Visual Studio 2008

Friday, April 18, 2008 10:17 AM by Me and my monkey

LINQ to SQL and Visual Studio 2008

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.