Reputation: 1858
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.
Upvotes: 2
Views: 75
Reputation: 31847
Yes, it's possible, using reflection. Also you can cast to Photographer
and then call SaveClients()
.
In my opinion a good solution is defining each group of actions you need to call in an interface, then, cast to that interface, and call the method you need:
public interface IBook
{
void BookClient();
void CancelClient();
}
public interface IClient
{
void SaveClients();
}
And then use as:
IBook photo = new Photographer();
// now cast photo object as a IClient
IClient client = photo as IClient;
if (client != null)
{
client.SaveClients();
}
Upvotes: 1
Reputation: 23300
Interface types can only reference interface members. You're attempting to invoke a member of the class which is not part of the interface.
You can try (can't test right now):
IBook photo;
photo = new Photographer();
(photo as Photographer).SaveClients();
// or
((Photographer)photo).SaveClients();
Upvotes: 2
Reputation: 125620
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.
Upvotes: 11