what is extension method in c#

11 votes
139 views
Pawan Shukla asked 13-Nov-2017 in programming by Pawan Shukla

what is extension method in c#

1 Answer

0 votes
Arti Mishra answered 16-Aug-2018 by Arti Mishra
"Extension Methods in C# "
An extension method is special types of static method of a static class, where the "this" keyword is used as a first parameter of this method. And Extension methods allow existing classes to be extended without inheritance or also allow to change the source code of existing class.
You can also use an extension method, in whole project by including the namespace of an extension method.

Here is the simple example where we demonstrate the example of an extension method-
ClassTest.dll

using System;
using System.Text;
namespace ClassTest
{
    public class Class1
    {
        public string Display()
        {
            return ("Display Method Called");
        }
    }
}

ExtensionMethod.dll

using System;
using System.Text;
using ClassTest;
namespace ExtensionMethod
{
    public static class ABCD
    {
         public static void NewExtensionMethod(this Class1 ob)
        {
            Console.WriteLine("Hello!...E xtended method called");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class1 obj = new Class1();
            obj.Display();
            obj.NewMethod();
            Console.ReadKey();
        }
    }
}