जगदीश खोलिया: April 2013

Monday, April 29, 2013

Extension Methods

Extension methods allow you to easily extend a type, such as an integer or string, without re-compiling or modifying the type or Extension methods enable you to "add" methods to existing types without creating a new derived type. Extension methods are a special kind of static method (shared in vb) , but they are called as if the method is native to the type.
One important thing to extension methods is if that you create an extension method with the same name as another method in that type, the compiler will bind the method call to the native method, not any extension. An extension method is only called when there is no native method found.

Steps To Create Extension Methods?
  1. Create a public static class. e.g. :  public static class Extensions{  }
  2. Define functions. 
     public static class Extensions
     {
      public string GetFirstThreeCharacters(String str)
      {
        if(str.Length < 3)
        {
            return str;
        }
        else
        {
            return str.Substring(0,3);
        }
      }
    }
  3. Make the functions an extension method.
To make our C# version of our function, we need an extension method to mark the function as static (so that it can be accessed at any time without the need for declaring anything) and secondly, mark the first parameter with the this keyword. This keyword basically tells the CLR that when this extension method is called, to use "this" parameter as the source. See the following:
 public static class Extensions
 {
    public static string GetFirstThreeCharacters(this String str)
    {
        if(str.Length < 3)
        {
            return str;
        }
        else
        {
            return str.Substring(0,3);
        }
      }
  }