What is the rationale behind explicit interface implementation? What problem/feature does it solve?
Or, put in other words, why .Net designer inserted explicit interface implementation in the language?
C# is a language that usually makes hard "shoot on your feet": as a simple example, it forces you to assing a variable before using it.
Explicit interface implementation goes on the opposite direction: it can make you easy to get an unexpected result from your code. Take this example:
interface IInterface
{
int Compute(List<int> values);
}
class MyClass: IInterface
{
public virtual int Compute(List<int> values)
{
//return count of list, null checks omitted
return values.Count;
}
int IInterface.Compute(List<int> values)
{
// different implemention for Compute
//return count of even numbers within the list, null checks omitted
return values.Where(x => x%2==0).Count();
}
}
public void Test()
{
List<int> values = new List<int>(new int[]{1, 2, 3, 4, 5});
MyClass c = new MyClass();
IInterface i = c; //no need for casting: MyClass implements IInterface
Console.WriteLine("Are they the same object? {0}", object.ReferenceEquals(c, i)); // print true, obviously
int res1 = c.Compute(values);
int res2 = i.Compute(values);
Console.WriteLine($"res1 ={res1}, res2= {res2}"); // ops, different results calling the same method on the same object
// output is: res1 =5, res2= 2
}
I understand why it runs in that way: if the method Compute is called from an IInterface reference, it calls the explicit interface method. if it's called from a MyClass reference, it call the "regular" method.
And I also understand that I should implement on method delegating to the other (or not using interface implementation at all).
But why the language needs this strange construct? what if simply it did not exist in the language?