Saturday, September 4, 2010

Extension Methods

Extension methods behavior is similar to that of static methods. You can declare them only in static classes. To declare an extension method, you specify the keyword this as the first parameter of the method, for example

static class StackOps
   public static void Push<T>(this List<T> TheList, T Value)

   public static T Pop<T>(this List<T> TheList)
      if (TheList.Count == 0)
         throw new Exception("Nothing to pop.");
      int LastPos = TheList.Count - 1;
      T Result = TheList[LastPos];

      return Result;

static void Main(string[] args)
   var Stack = new List<int>();

   // Put stuff onto the stack.
   for (int i = 0; i <= 10; i++)

   // And now pop stuff off it.
   while (Stack.Count > 0)

Read more about Extension Methods here.

No comments:

Post a Comment