Why do explicit C# interface calls within a generic method that has an interface type constraint always call the base implementation?
For example, consider the following code:
public interface IBase
{
string Method();
}
public interface IDerived : IBase
{
new string Method();
}
public class Foo : IDerived
{
string IBase.Method()
{
return "IBase.Method";
}
string IDerived.Method()
{
return "IDerived.Method";
}
}
static class Program
{
static void Main()
{
IDerived foo = new Foo();
Console.WriteLine(foo.Method());
Console.WriteLine(GenericMethod<IDerived>(foo));
}
private static string GenericMethod<T>(object foo) where T : class, IBase
{
return (foo as T).Method();
}
}
This code outputs the following:
IDerived.Method
IBase.Method
Instead of what one might expect:
IDerived.Method
IDerived.Method
There seems to be no way (short of reflection) to call a hidden, more derived explicit interface implementation of a type decided at runtime.
EDIT: To be clear, the following if check evaluates to true in the GenericMethod call above:
if (typeof(T) == typeof(IDerived))
So the answer is not that T is always treated as IBase due to the generic type constraint "where T : class, IBase".
IDerived.Method
in the first place? Besides having the same nameIBase.Method
andIDerived.Method
are not related. – SloppyGenericMethod
is specifyingIBase
? – Reportorialnew
) is generally bad. – Carrel