Thursday, January 20, 2011

Extension Methods in C#

Extension methods allow developers to extends the functionality of an existing type without creating a new derived type.
Simple Extension Method Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace extmethods
{
  //This class Must be Public.
  // even sealed classes can extends by extension methods

  public sealed class human
  {
      public void eat()
    {
  Console.WriteLine("Eat Food");
   }
 
}
 
 ///

  /// This is my human Extensions class.This class must be static.
/// 

  public static class humanextension
  {
  /// This is our extension method for the human class.The first argument of a class extension should always be named "this" and should have the Type of the Type you want to extend.In this example class human is being Extend.Thats why argumentof the method contains this human objectname.This method must be static.
 
 
    public static void eatpkfood(this human h)
   {
    Console.WriteLine("Eat Pak Food");
   }
}
  class Program
 {
  static void Main(string[] args)
    {
  human extmethod = new human();

 /// The following line used the "eatpkfood" extension method.You can see that object of human class acesses the method of humanextension  class.

 extmethod.eatpkfood();
//This line invokes the "eatpkfood" method of humanextension class.
humanextension.eatpkfood(extmethod);
 Console.Read();
    }
 }
}

OUTPUT:
Eat Pak Food
Eat Pak Food