Home > Software design >  How to use default interface methods in specific class?
How to use default interface methods in specific class?

Time:04-29

public interface IPrinter
{
    public void Print()
    {
       Console.WriteLine("Printing...");
    }
}

public interface IScanner
{
    public void Scan()
    {
       Console.WriteLine("Scanning...");
    }
}

public class Copier : IPrinter, IScanner
{
    public void ScannAndPrint()
    {
       Scan();
       Print();
       Console.WriteLine("Scanning and Printing complete!");
    }
}

I get the following compiler errors:

CS0103 "The name 'Scan' does not exist in the current context"

CS0103 "The name 'Print' does not exist in the current context"

How to achive this kind of concept? I want to use default interface methods feature.

CodePudding user response:

To use default interface implementations, you have to cast your variable to the type of the corresponding interface:

public void ScannAndPrint()
{
   ((IScanner)this).Scan();
   ((IPrinter)this).Print();
   Console.WriteLine("Scanning and Printing complete!");
}

Online-demo: https://dotnetfiddle.net/sudQJn

  • Related