The example below is contrived/simplified but displays the issue I am seeing.
Interface with a static method.
Base class that implements interface.
Two derived classes. One implicitly implements interface because base class does. One explicitly states the interface implementation (even though it doesn't need to).
Calling the static method directly on the derived classes works as expected.
Calling the static method from within a generic helper class calls the wrong static method if the interface was not explicitly stated by the derived class.
Or is this expected behavior (and why)?
I have also tried having FooBase not implement the method. Then I have to remove the new keyword from both derived classes. In this case, the IFoo implementation gets called in the implicit case when calling through the generic type.
namespace TestConsole.TestStaticMethodOverride2;
internal class Program
{
static void Main(string[] args)
{
FooDerivedImplicit.Do();
Console.WriteLine();
FooDerivedExplicit.Do();
Console.WriteLine();
GenericCallStatic<FooDerivedImplicit>.Call();
Console.WriteLine();
GenericCallStatic<FooDerivedExplicit>.Call();
Console.WriteLine();
}
}
public interface IFoo
{
public static virtual void Do() => Console.WriteLine("IFoo:Do");
}
public class FooBase : IFoo
{
public static void Do() => Console.WriteLine("FooBase:Do");
}
public class FooDerivedImplicit() : FooBase // Implicitly IFoo
{
public static new void Do() => Console.WriteLine("FooDerivedImplicit:Do");
}
public class FooDerivedExplicit() : FooBase, IFoo // Explicitly says is IFoo
{
public static new void Do() => Console.WriteLine("FooDerivedExplicit:Do");
}
public static class GenericCallStatic<T> where T : IFoo
{
public static void Call() => T.Do();
}
Outputs
FooDerivedImplicit:Do
FooDerivedExplicit:Do
FooBase:Do
FooDerivedExplicit:Do