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...
}
See also
How to suppress compiler generated warnings in Visual Studio
Delegates Vs. Interface
Partial Methods in C#
This comment has been removed by a blog administrator.
ReplyDelete