Extension methods

What are extension methods?

Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or modifying the original type.

An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.

Extension is done by using "this" modifier applied to the first parameter. The type of the first parameter will be the type that is extended.

Extension methods are only in scope where you import the namespace.

...
using ClassLibExtMethod;
namespace ExtensionMethod1
{
    public static class XX
    {
         public static void NewMethod(this Class1 ob)
         {
            Console.WriteLine("Hello I m extended method");
         }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class1 ob = new Class1();
            ob.Print();
            ob.NewMethod();
        }
    }
}

Know More

results matching ""

    No results matching ""