Explicit interface implementation in .NET

The generic and well-known Dictionary object and its generic and thread-safe counterpart, i.e. the ConcurrentDictionary object both implement the generic IDictionary interface. The IDictionary interface has an Add method where you can insert a new key-value pair into a dictionary:

It does indeed. At least the code compiles and Visual Studio can run the code.

How and why did this happen? Why is the Add method available for the Dictionary class and not the ConcurrentDictionary class if they are both IDictionary objects? This is made possible by a C# language feature called explicit interface implementation.

…implementation is an implicit implementation of the generic IEnumerable of T interface which returns an IEnumerator of T object.

The other method, i.e.

IEnumerator IEnumerable.GetEnumerator()

…is an explicit implementation of the non-generic IEnumerable interface which is inherited by the generic IEnumerable of T interface. Hence when we implement the generic IEnumerable of T interface we have to implement both the generic and the non-generic GetEnumerator methods.

Let’s first see how this language structure works in C#. Suppose we have the following interface:

We assume here that we cannot change the method names of ISummable and IMultipliable. They may be part of a third party library. One way out of this situation is to implement IMultipliable explicitly. If you right-click “IMultipliable” in Calculator.cs in Visual Studio you can select “Implement Interface”, “Implement Interface Explicitly” in the context menu. You’ll get the following stub:

The Add method of the IDictionary interface is explicitly implemented by the ConcurrentDictionary object. That’s why the Add method is not available directly on ConcurrentDictionary whereas it is available if we declare ConcurrentDictionary as an interface type:

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: