Monday, February 16, 2015

Partial Interfaces in C#

Not only classes, structs or methods can be declared as partial. We can define interfaces as partial as well. If you want to learn more about partial classes, do read my previous post about partial classes in the context of Portable Code Strategies for Windows Store and Windows Phone 8 App Development. The concept is pretty much the same when comes to partial Interfaces and here is how we define partial Interfaces.
partial interface IMyInterface
{
    void MyMethod1();
}
 
partial interface IMyInterface
{
    void MyMethod2();
}
 
public class MyClass : IMyInterface
{
    public void MyMethod1()
    {
        Console.WriteLine("Called MyMethod1");
    }
 
    public void MyMethod2()
    {
        Console.WriteLine("Called MyMethod2");
    }
}
Here I have the Interface IMyInterface which I declared as partial and I have a class named MyClass which implements it. In my class I am implementing  both MyMethod1 and MyMethod2 just as I would do for implementing non partial Interfaces. And I can invoke the methods as follows.
static void Main(string[] args)
{
    IMyInterface myInterface = new MyClass();
    myInterface.MyMethod1();
    myInterface.MyMethod2();
}

Pretty simple, isn’t it.

Happy Coding.

Regards,
Jaliya