Saturday, September 23, 2017

Extension method

Extension methods are static methods of a static class, that can be invoked like an instance method of the extended type.

Extension methods enable us to “add” methods to an existing Types without creating a new derived type, recompiling, or otherwise modifying the original type.

In extension method, “this” keyword is used with the first parameter and this first parameter will be of type that is extended by the extension method.

Public static class MyExtensions {
   public static int WordCount(this, String str)
   {
      return str.Split(new Char[] {‘ ‘ , ‘.’ , ‘,’}).Length;
   }
}
Public Static void Main()
{
    string s = “……”;
    int count = s.WordCount();//
                                   // or int count = MyExtensions.WordCount(s);
}

Linq’s Standard Query operators, like Select, Where etc,  are implemented in Enumerable Class as Extension methods on the IEnumerable<T> interface.
eg. List<int> Numbers = new List<int> {1,2,3,4,5,6,7,8,9,10};
IEnumerable<int> EvenNumbers = Numbers.Where( n => n%2 == 0);
                                                  
Above, inspite of “Where()” method not belonging to List<T> Class, we are still able to use it as if belongs to List<T> Class.  This is possible because Where() method is implemented as Extension Method in IEnumerable<T> interface and List<T> implements IEnumerable<T> interface.

Note that above Extension method can also be called by using the Wrapper Class Style Syntax. In fact, behind the scene this is how the extension method actually gets called.ie.
IEnumerable<int> EvenNumbers = Enumerable.Where(Numbers, n => n%2 == 0);

This means that we should also be able to call Linq extension methods (Select, Where etc) using wrapper class style syntax , since all linq extension methods are defined in Enumerable Class, the syntax will be as shown below.

List<int> Numbers = new List<int> {1,2,3,4,5,6,7,8,9,10};
       IEnumerable<int> EvenNumbers = Enumerable.Where(Numbers, n => n%2 == 0);

Public static class StringHelper
{
    public static string  ChangeFirstCaseLetter(this string inputString)
       {
             if(inputString.Length > 0)
                {
    char[] charArray = inputString.ToCharArray();
    charArray[0] = char.IsUpper(charArray[0]) ?
           char.ToLower(charArray[0]) : char.ToUpper(charArray[0]);

   return new string (charArray);  
}
return inputString;
}
}
public void Main
{
    string strName = “The Quick Brown Fox”;
    string result = strName.ChangeFirstCaseLetter();
      
     //or result = StringHelper.ChangeFirstCaseLetter(strName);         
    //wrapper class style   syntax     
                                                                                      
}

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More