Search code examples
c#.netoopinterfacedefault-interface-member

How can we use default implementation of different interfaces?


As I know, I need to upcast an instance of an inherited class to the interface where a needed method is implemented and then call it.

interface IProcess
{
    void Do() { Console.WriteLine("doing"); }
    //...
}

interface IWait
{
    void Wait() { Console.WriteLine("waiting"); }
    //...
}

class Example : IProcess, IWait { }


static void Main(string[] args)
{
    Example item = new Example();
    (item as IProcess).Do();
    (item as IWait).Wait();
}

What if there are few interfaces with default implementation of different methods that I need? Is there some pattern that can solve this or maybe I should always use as keyword to call a method of a certain interface?


Solution

  • Another option in addition to @DavGarcia's answer - introduce an interface combining the needed ones and upcast to it:

    interface IExample : IProcess, IWait { }    
    class Example : IExample { }
    
    IExample item = new Example();
    item.Do();
    item.Wait();