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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With