Hardik B Bhilota
Hardik B Bhilota

Reputation: 207

How to access additional method of class that implemented interface

As shown in below code, I have created Sample class which implements the IPrint interface's Print method and it also has additional SampleTest method. In main section I create object of Sample class and assign it to interface. However what if I want to access SampleTest method.

Also what are the thoughts on this code? Is it ok to implement SampleTest additional method and call it from main?


interface IPrint
{
    void Print();
}

class Sample : IPrint
{
    public void Print()
    {
        Console.WriteLine("Print...");
    }

    public void SampleTest()
    {
        Console.WriteLine("SampleTest...");
    }
}

class Program
{
    static void Main(string[] args)
    {
        IPrint print = new Sample();
        print.Print();
        // How would I access SampleTest methos of Sample class here
    }
}

Upvotes: 1

Views: 451

Answers (2)

Alexander Lisitsyn
Alexander Lisitsyn

Reputation: 111

The goal of the interface is provide a contract to work with classes that implement this interface. The benefit of this - you don't care about concrete implementation.

So, while your interface IPrint doesn't contain SampleTest() method you can't access it from object wich type is IPrint.

The only way, is casting your object to Sample class, as already been said, but I think it will be bad design, because you come back to concrete implementations.

Consider to call SampleTest() method from your Print() method if you need some additional actions to perform while print proccess. This way, your main() still doesn't care about which printer is used right now.

Upvotes: 2

Guanxi
Guanxi

Reputation: 3131

Since object is of type sample and you assigned to IPrint so you cannot access SampleTest unless you cast your print object to Sample. This should work:

((Sample)print).SampleTest();

Upvotes: 0

Related Questions