Friday, December 2, 2011

Extension Methods: Straight to the Point!

I kept looking at many articles on extension methods and for some reason I couldn't get mine to work. It then dawned on me that the class where you declare you extension methods MUST BE STATIC. That is a gotcha and for some reason it isn't emphasized even though all of the examples clearly have static classes and methods.

The basics of extension methods are:

  1. Static Class
  2. Static Methods
  3. Use the "this" keyword to in order to infer what is expected to use the extension method

//Basic example
public static class CustomExtentionMethodsClass
{
    public static void IncrementAllByNumber(this List list, int intValue)
    {
        for(int i; i < list.Count; i++)
            list[i] += intValue;
    }
}

//Usage
List lstOfInt = new List();

lstOfInt.Add(1);
lstOfInt.Add(2);
lstOfInt.Add(3);

lstOfInt.IncrementAllByNumber(2);

//Elements should all be incremented by 2
//2
//4
//5