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