Explicit Interface Implementation !!!

I have encountered this [wait i’ll explain] sort of situation many times and I mostly do this way in C++.

Assume you have a class CMyClass that exposes its functionality through its public methods, and also let it listen to events from some sources, events being OnSomeEvent or OnXXXX(), by implementing some event interface IXModuleEvents. Now these event listener methods are reserved only for internal use and are not meant to be called by the users. So when I implement the IXModuleEvents interface in CMyClass, I make them private. Think about it and the problem is solved. It is the polymorphism game, that never cares for the accessibility of the method.

But I was in the same situation and my head had stopped working and my hands went coding the same way, and found that it does not work. In C#, i have the facility to declare a interface and by default its methods are public, strictly no need of any access specifiers. And the class that implements has to implement it publicly. So my OnXXX() methods get exposed.

But yes, there is a solution for the situtation, it is called Explicit Interface Implementation. It is this way:-

internal interface IXModuleEvents
void OnSomeEvent(int i, int j);
void OnSomeOtherEvent(string name);

public class CMyClass : IXModuleEvents
// ..... Other implementation

// No need of any access specifiers
void IXModuleEvents.OnSomeEvent(int i, int j)

// No need of any access specifiers
void IXModuleEvents.OnSomeOtherEvent(string name)

So you can access these OnXXXX() method implementation only if you have a IXModuleEvents reference of the CMyClass, and try out with a CMyClass reference to access the event listener method implementation.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s