C#

Extension Methods in C#

Extension methods enable us to add methods to existing types without creating a new derived type, recompiling, or making any modification in the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type. For a programmer written the code, there's no apparent difference between calling an extension method and the methods defined in a type.

The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types. 

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter is preceded by the “this” modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a “using” directive.

The following example shows an extension method defined for the String class. It's defined inside a non-nested, non-generic static class:

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

The following example shows the use of the extension method on a string variable.

using System;
//The WordCount extension method can be brought into scope by just including the ExtensionMethods namespace
using ExtensionMethods;

namespace DemoForExtenstionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "This is Ajith";
            //The extension method can be called just like any instance method
            int count = str.WordCount();
            Console.WriteLine(string.Format("Total Words {0}", count));
            Console.ReadLine();
        }
    }
}

Please note that the extension methods are used to extend a class or an interface and not overriding existing methods in it. An extension method with the same name and signature as that of an instance method will never be called. When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds.

Resources and References from:

  1. Microsoft Docs