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#

1 comment: