Pages

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)
   {
      TheList.Add(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];

      TheList.RemoveAt(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++)
      Stack.Push(i);

   // And now pop stuff off it.
   while (Stack.Count > 0)
      Console.WriteLine(Stack.Pop());
}

Read more about Extension Methods here.

No comments:

Post a Comment