Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access the other members of an interface type?

Tags:

c#

I'm curious if this is possible, and if not, what are the reasons behind it if any, and how would one handle this programming scenario?

Let's say i have this interface:

public interface IBook
{
    void BookClient();
    void CancelClient();
}

and i have this class that implements the above interface:

public class Photographer : IBook
{
     public void BookClient()
     {
        // do something
     }

     public void CancelClient()
     {
        // do something
     }

     // non-interface methods
     public void SaveClients()
     {
        // do something
     }

     public void DeleteClients()
     {
        // do something
     }
} 

Now if I assign this class to an interface type somewhere in my code such as:

IBook photo;
photo = new Photographer();

Is it possible to do this:

// non-interface member from the Photographer class
photo.SaveClients();

Can someone straighten me out on this issue and perhaps point me in the right direction regarding this. Thanks.

like image 226
user1206480 Avatar asked Jan 29 '26 12:01

user1206480


1 Answers

Yes, it's possible, but you have to cast your photo into Photographer first:

// non-interface member from the Photographer class
((Photographer)photo).SaveClients();

It's not possible with just photo.SaveClients() syntax, because you can easily create another class:

class TestClass : IBook
{
    public void BookClient()
    {
       // do something
    }
     public void CancelClient()
    {
       // do something
    }
}

And use it like that:

IBook photo;
photo = new Photographer();
photo = new TestClass();

// what should happen here?
photo.SaveClients();

So as long as you use the variable as an interface implementation, you can only access member declared in that interface. However, the object is still a class instance, so you can use other class members, but you have to explicitly cast to that type first.

like image 127
MarcinJuraszek Avatar answered Jan 31 '26 01:01

MarcinJuraszek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!