'How to use default interface methods in specific class?

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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SomeBody