Explicit interface implementation in .NET Part 4
August 14, 2015 2 Comments
In the previous post we finally solved the mystery of how the Add method was “hidden” in the ConcurrentDictionary object. We now know how explicit interface implementation works in code.
However why would you implement an interface explicitly?
I can think of two reasons:
Method signatures
In C# two methods are considered the “same” if they have the same name and same input parameter types. Their return type doesn’t matter. The following code will cause the compiler to complain:
public bool Method(int i) { return false; } public int Method(int input) { return input + 2; }
Those two methods have the same method signatures and cannot be overloaded based on their return types only. Consequently if you have two interfaces that provide methods of the same signature, like we saw before…:
public interface ISummable { int Calculate(int a, int b); }
public interface IMultipliable { int Calculate(int a, int b); }
…then the only option two implement both is to implement at least one of them explicitly. It doesn’t make any difference which. You can implement both of them explicitly as well.
Discourage usage
The above reasoning doesn’t explain why the Add method is not available directly on the ConcurrentDictionary object.
In that specific case Microsoft wanted to discourage the usage of the Add method which was meant for single-threaded usage just like in the “normal” Dictionary object. ConcurrentDictionary is meant to be used in multithreaded scenarios. The Add method was therefore explicitly implemented instead. It’s unlikely that people will declare a concurrent dictionary as an interface type:
IDictionary<string, string> concurrentDictionary = new ConcurrentDictionary<string, string>();
Therefore if you declare the ConcurrentDictionary like most people do…
ConcurrentDictionary<string, string> concurrentDictionary = new ConcurrentDictionary<string, string>();
…then you’ll be instead presented with the thread-safe TryAdd and AddOrUpdate methods so you’ll automatically be “redirected” to those methods.
So if you’d like to hide an implicit interface method from the consumers of an object an option is explicit interface implementation so that the interface method won’t be visible on the class.
This post concludes our discussion of explicit interface implementation.
View all various C# language feature related posts here.
Reblogged this on Dinesh Ram Kali..
very good -) as always ur efforts are deeply appreciated..