Default interface implementation shouldn't be virtual #9434
-
At the time of design, it seems that the intention was for the default interface methods to be overridable, but that idea was abandoned. This raises the question: Why would they need to be virtual? These methods do not fulfill the requirements for being virtual. They are stored in the virtual method table and take up space. Additionally, calling them requires instructions for calling virtual methods, which can affect JIT and consequently its performance. Default interface methods are no different from method extensions, except they can only be called for an interface. Method extensions allow you to do this for inherited types for obvious reasons. It seems like a mistake that they can't be overridden, as this give them only an aesthetic function and negatively affect their use of a virtual method table for no reason. interface Interface1
{
void Display() => Console.WriteLine("Interface1");
}
struct Struct1 : Interface1;
interface Interface2;
struct Struct2 : Interface2;
static class Extensions
{
public static void Display(this Interface2 self) => Console.WriteLine("Interface2");
} Interface1 value = default(Struct1);
value.Display(); // OK
Interface2 value = default(Struct2);
value.Display(); // OK struct Struct1Ex : Interface1
{
public override void Display() => Console.WriteLine("Struct1Ex"); // CS0115: no suitable method found to override
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Not sure what you mean, DIMs are overridable, just not like that. Just remove the struct Struct1Ex : Interface1
{
public void Display() => Console.WriteLine("Struct1Ex");
} You can also implement it explicitly: struct Struct1Ex : Interface1
{
void Interface1.Display() => Console.WriteLine("Struct1Ex");
} |
Beta Was this translation helpful? Give feedback.
Not sure what you mean, DIMs are overridable, just not like that. Just remove the
override
keyword and it works.https://sharplab.io/#v2:C4LgTgrgdgPgAgJgIwFgBQ6CSVgFMwBmAhgMa5IAEAbkQDYS4UC8FAJrsRLcABQDKwSCWBIAlAG50NergB0AEQCWAZwAOtIgE8eE9OkU58xMhWx5CpcugDe6CvYpwALBSVqN20cwB8jpAE4eACIzI0skIN00AF89NGVBCGEKASERChBTQwsyVDRbNAc4AGZHFzd1LR0fP0Cg1KSRAFEAD0jJGKA=
You can also implement it explicitly: