Why is the behavior of Default Interface Methods changed in C# 8? In the past the following code (When the Default interface methods was demo not released):
interface IDefaultInterfaceMethod
{
// By default, this method will be virtual, and the virtual keyword can be here used!
virtual void DefaultMethod()
{
Console.WriteLine("I am a default method in the interface!");
}
}
interface IOverrideDefaultInterfaceMethod : IDefaultInterfaceMethod
{
void IDefaultInterfaceMethod.DefaultMethod()
{
Console.WriteLine("I am an overridden default method!");
}
}
class AnyClass : IDefaultInterfaceMethod, IOverrideDefaultInterfaceMethod
{
}
class Program
{
static void Main()
{
IDefaultInterfaceMethod anyClass = new AnyClass();
anyClass.DefaultMethod();
IOverrideDefaultInterfaceMethod anyClassOverridden = new AnyClass();
anyClassOverridden.DefaultMethod();
}
}
has the following output:
Console output:
I am a default method in the interface!
I am an overridden default method!
But with the C# 8 last version the code above is producing the following output:
Console output:
I am an overridden default method!
I am an overridden default method!
Anyone can explain to me why this behavior is changed?
Note:
IDefaultInterfaceMethod anyClass = new AnyClass(); anyClass.DefaultMethod();
((IDefaultInterfaceMethod) anyClass).DefaultMethod(); // STILL the same problem!??
I suspect a better question would be:
The feature was planned but was cut from C# 8 in April 2019, because an efficient implementation would require support from the runtime. This couldn't be added in time before release. The feature would have to work well both for C# and VB.NET - F# doesn't like interfaces anyway.
It will work through a
base()
call similar to how classes work. Coopying the proposal example :