I try to use the new C# default interface methods. Can anyone explain the following code and why this happens?
Minimal test example:
public static void Main()
{
Class c = new Class();
IInterface i = new Class();
c.M1();
i.M1();
(i as IInterface).M1();
Class2 c2 = new Class2();
Class2Base c2b = new Class2();
c2.M2();
c2b.M2();
(c2 as Class2Base).M2();
}
public interface IInterface
{
public void M1() => Console.WriteLine("Call from interface");
}
public class Class : IInterface
{
public void M1() => Console.WriteLine("Call from class");
}
public class Class2 : Class2Base
{
public void M2() => Console.WriteLine("Call from class2");
}
public class Class2Base
{
public void M2() => Console.WriteLine("Call from class2base");
}
Outputs:
Call from class
Call from class
Call from class
Call from class2
Call from class2base
Call from class2base
I expect to see "Call from interface" in the second call similar to when using normal inheritence like in the second example.
To summarize:
Why is the interface method hidden and (maybe) how can i still call it.
Also, this is my first question here so any tips are welcome
Class
implementsM1
, so it is called. If you make another class that "implements IInterface" but in which you do not implementM1
, then the default from the interface is called. It has only marginally to do with "classic" inheritance.class2
noting that there is a possible unintentional shadowing there. If you intend there to be two non-virtual methods with the same name, the convention is to tell the compiler that this is not a mistake by decorating the shadowing method withnew
. If you intend the shadowing method to be a virtual override, you need to mark the original method asvirtual
and the new method asoverride
.