Explicit interface implementation in .NET Part 3
August 12, 2015 3 Comments
In the previous post we started looking into how explicit interface implementation is done in code. Visual Studio makes it a breeze and you can easily produce code like we saw previously:
int IMultipliable.Calculate(int a, int b) { ... }
So now we can reach the Calculate methods as follows:
Calculator calc = new Calculator(); int calcCalculate = calc.Calculate(2, 5); ISummable summable = new Calculator(); int calcSummable = summable.Calculate(2, 5); IMultipliable multiplier = new Calculator(); int calcMultiplier = multiplier.Calculate(2, 5);
“calcCalculate” will be 7 as we call the Calculate method of the Calculator object. It was implicitly implemented from the ISummable interface.
“calcSummable” will also be 7 of course, as it calls the same implementation as above.
“calcMultiplier” will be 10 as it calls the explicitly implemented Calculate method of the IMultipliable interface.
There’s nothing stopping us from implementing both interfaces explicitly and remove the implicit Calculate implementation:
public class Calculator : ISummable, IMultipliable { int IMultipliable.Calculate(int a, int b) { return a * b; } int ISummable.Calculate(int a, int b) { return a + b; } }
If we do that then the following code will cause the compiler to complain:
Calculator calc = new Calculator(); int calcCalculate = calc.Calculate(2, 5);
There’s no Calculate method defined for the Calculator object any more.
This solves the mystery behind the Add method of ConcurrentDictionary of the first part of this mini-series:
ConcurrentDictionary<string, string> concurrentDictionary = new ConcurrentDictionary<string, string>(); concurrentDictionary.Add("Key", "Value");
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:
IDictionary<string, string> concurrentDictionary = new ConcurrentDictionary<string, string>(); concurrentDictionary.Add("Key", "Value");
We still haven’t discussed why we’d ever choose to implement an interface explicitly. We’ll look into that in the next post which finishes this short series.
View all various C# language feature related posts here.
Awesome!,followed all three posts really good explanation.
That’s great to hear, thanks for your comment. //Andras
Reblogged this on Dinesh Ram Kali..