Pages

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?

publicstaticclassMyExtensionMethods

{

publicstaticvoidMyMethod(thisITestInterface Test)

{

Console.WriteLine("Extension Method...");

}

}

publicinterfaceITestInterface

{

void Display(string name);

}

publicclassTestClass : ITestInterface

{

publicvoid Display(string name)

{

Console.WriteLine("Hello" + name);

}

}

publicstaticvoid Main()

{

ITestInterface test = newTestClass();

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.

you have been shared really informative blog. before i read this blog i didn't have any knowledge about this but now i got some knowledge. so keep on sharing such kind of an interesting blogs.dot net training in chennai