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;

List lstOfInt = new List();



//Elements should all be incremented by 2

No comments:

Post a Comment