C-Sharp : Understanding Extension Methods

When we want to enhance the additional functionality as instance method then we use Extension Method. Extension Method represents static method as instance methods. We can use Extension Method as same as instance method. 

  
Extension Method
Extension Method always show with this image.

Extension Method can have one or more parameters. An Extension Method uses this keyword as its parameter list.

namespace ExtensionMethod
{
    public static class MyExtMethod
    {
        public static int CountWord(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}

The first parameter of Extension Method specifies which type the Method operates on, parameter is preceded by this keyword.

The scope of Extension Method is depend on, when we explicitly imports the namespace with using directive.

Using ExtensionMethod;

Point To Remember:

  • If Extension Method has same signature as a Method defind in the type then Extension Method will never be called.
  • Extension Method will work on namespace level means they are brought into scope at the namespace level.
  • At Compile Time, Extension Method always has lower priority than instance method.
  • If we have a method AccessData( int i) and also have an extension method with same signature then compiler will always bind instance method.
  • At Runtime compiler always look for instance method, if not found, then it will search for Extension Method.

Using ExtensionMethod;
class TestExtensionMethod   
{

    static void Main()
    {            
        string value ="Shashi Kiran Singh";
        int result = value.CountWord();
 Console.WriteLine(result);

      }        
}
//Output: 18


Tricks Always Work

Comments

Popular Posts