Tuesday, September 6, 2011

How to extend Interface using Extension Methods in C#


Extension methods are used to extend an existing type with new methods without changing original type. Extension methods were introduced in C# 3.0. Extension methods are defined as static method inside static class and the first parameter must be this. In this article I will explain how to extend interface using extension method?

public static class MyExtensionMethods
{
    public static void MyMethod(this ITestInterface Test)
    {
        Console.WriteLine("Extension Method...");
    }
}
public interface ITestInterface
{
    void Display(string name);
}
public class TestClass : ITestInterface
{
    public void Display(string name)
    {
        Console.WriteLine("Hello" + name);
    }
}
public static void Main()
{
    ITestInterface test = new TestClass();
    test.Display("Mitesh");  //Output - Hello, Mitesh
    test.MyMethod();    // Output - Extension Method...
}

As shown in above code, ITestInterface is extended with new method called MyMethod. To extend interface one static method MyMethod is created inside MyExtensionMethods static class. MyMethod has ‘this’ as first parameter and followed by the interface type (which we need to extend) in our case ITestInterface. We can also access properties of ITestInterface inside MyMethod using Test instance of ITestIterface.


See also
How to suppress compiler generated warnings in Visual Studio
Delegates Vs. Interface
Partial Methods in C#

3 comments:

  1. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. dot net training institute in velachery | dot net course fees

    ReplyDelete
  2. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training and placement in chennai | dot net training in chennai

    ReplyDelete