Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a concrete class hide a member of the interface that it implements

Tags:

c#

.net

I will give an example from .NET.

ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary

Here you can see ConcurrentDictionary implementing dictionary interfaces. However I can't access Add<TKey,TValue> method from a ConcurrentDictionary instance. How is this possible?

IDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();
dictionary.Add(3, 3); //no errors

ConcurrentDictionary<int, int> concurrentDictionary = new ConcurrentDictionary<int, int>();
concurrentDictionary.Add(3, 3); //Cannot access private method here

Update:

I know how I can access it but I didn't know explicitly implementing an interface could allow changing access modifiers to internal. It still doesn't allow making it private though. Is this correct? A more detailed explanation about that part would be helpful. Also I would like to know some valid use cases please.

like image 345
Ufuk Hacıoğulları Avatar asked Jan 11 '13 14:01

Ufuk Hacıoğulları


2 Answers

Because the IDictionary.Add method is explicitly implemented by ConcurrentDictionary.

To access it from the class without having to declare the variable as IDictionary, cast it to the required interface:

((IDictionary)concurrentDictionary).Add(3, 3)
like image 194
stuartd Avatar answered Oct 20 '22 17:10

stuartd


This is done through explicit interface implementation

public interface ISomeInterface
{
    void SomeMethod();
}

public class SomeClass : ISomeInterface
{
    void SomeInterface.SomeMethod()
    {
        // ...
    }
}

Now when you have a reference to a SomeClass object, you will not see the SomeMethod method available. In order to call it you would have to cast the object back to ISomeInterface...

((ISomeInterface)mySomeClass).SomeMethod();

This is one of the more under-utilizied useful features of C# imo

like image 37
MattDavey Avatar answered Oct 20 '22 17:10

MattDavey