Hiding properties and methods of an interface in C#

Recently I began to wonder how people hide some of the methods in their classes that are part of the interfaces that the class implements. One of the concrete examples is BindingList(T) class: it implements IBindingList interface but does not expose methods such as AddIndex at all.

The answer to the question is explicit interface implementation. Well, as always, I have read about it before but didn’t really understand the use of it until I faced a real world situation where it came handy. I’ll explain how it works shortly:

Let’s suppose you have the following interface and class that implements it:

public interface ISample
{
    void InterfaceMethod();
    void SecondInterfaceMethod();
}

public sealed class Sample: ISample
{
    public void InterfaceMethod()
    {
        // do something here
    }

    public void SecondInterfaceMethod()
    {
        // do something else here
    }
}

Now let’s suppose that in the class Sample, you don’t want the method to be seen by users of this class (method is not implemented, does not relate to the class or something else). The interface requires you to have this method though. It is now when explicit interface implementation comes in. To hide the SecondInterfaceMethod method you’d do the following:

public sealed class Sample: ISample
{
    public void InterfaceMethod()
    {
        // do something here
    }

    void ISample.SecondInterfaceMethod()
    {
        // do something here that should be used only by ISample interface
    }
}

The method name is preceded by interface name and a dot now. Note that access modifiers (public in this case) are not needed now for SecondInterfaceMethod. Visual Studio will warn you about it. Now the class implements the interface but the SecondInterfaceMethod is not visible to the outside of class, until you cast an instance of Sample to ISample interface. So the method is implemented to be used by the interface explicitly:

Sample sampleClass = new Sample();

// gives compile time error, since the method is not visible from Sample class
sampleClass.SecondInterfaceMethod();

// will work as expected
((ISample)sampleClass).SecondInterfaceMethod();
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s