Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading