Explicit interface implementation in .NET Part 2
August 11, 2015 1 Comment
In the previous post we introduced the idea of explicit interface implementation in .NET. We also saw two examples from .NET with explicit implementation in action.
Let’s first see how this language structure works in C#. Suppose we have the following interface:
public interface ISummable { int Calculate(int a, int b); }
We can then implement this interface implicitly as follows:
public class Calculator : ISummable { public int Calculate(int a, int b) { return a + b; } }
This should be straightforward for all programmers.
Let’s have another interface:
public interface IMultipliable { int Calculate(int a, int b); }
We then want our calculator to implement the above interface as well:
public class Calculator : ISummable, IMultipliable { public int Calculate(int a, int b) { return a + b; } }
As Calculator already has a Calculate method with two integer parameters it also satisfies IMultipliable without changing the Calculator object implementation.
This is problematic as we have no straightforward way to provide a multiplication for our calculator:
Calculator calculator = new Calculator(); int res = calculator.Calculate(2, 5);
“res” will be 7 of course.
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:
public class Calculator : ISummable, IMultipliable { public int Calculate(int a, int b) { return a + b; } int IMultipliable.Calculate(int a, int b) { throw new NotImplementedException(); } }
The structure of the new Calculate method looks very much like the non-generic GetEnumerator method of the second example of the previous post.
Explicitly implemented interface methods must not have any access modifiers. They are public by default.
Let’s implement the new method:
int IMultipliable.Calculate(int a, int b) { return a * b; }
How can we call this method? We have to declare Calculator as an interface type:
public void ShowSample() { IMultipliable calculator = new Calculator(); int res = calculator.Calculate(2, 5); }
“res” will now be 10.
We’ll investigate this further in the next post.
View all various C# language feature related posts here.
Reblogged this on Dinesh Ram Kali..