Home > Software engineering >  Why isn't keyword override used when implementing methods from interfaces? C#
Why isn't keyword override used when implementing methods from interfaces? C#

Time:08-01

interface A1 {
    void jj();
    void ff() { /*  */}
}

class B1 : A1 {
    public void jj() { }
    void ff() { /*  */}
}

I am implementing two methods in the B1 class: the jj(), which does not have a default implementation in the interface A1, and the ff(), which does have a default implementation in the interface A1.

I am wondering why do not we use the override keyword when implementing a method from an interface since those methods in the interfaces are wither abstract or virtual?:
jj : abstract
ff : virtual

10 years ago, you could say that it is because the interface does not have a deafult implementation and taht is why we do not override, we implement, BUT starting from C# 8.0 , default implementations are possible and so why is that that we are not OBLIGED to use the override keyword?

CodePudding user response:

from c# 8 docs

The final override for IA.M in class C is the concrete method M declared in IA. Note that a class does not inherit members from its interfaces; that is not changed by this feature:

as the interface implementation is not inherited by its children there is no need to override it every declaration of an interface method by its child is the only implementation the child can have.

CodePudding user response:

As msdn docs says about Default interface members:

These preceding member declarations typically don't contain a body. Beginning with C# 8.0, an interface member may declare a body. Member bodies in an interface are the default implementation. Members with bodies permit the interface to provide a "default" implementation for classes and structs that don't provide an overriding implementation.

and:

Beginning with C# 11, an interface may define static abstract or static virtual members to declare that an implementing type must provide the declared members. Typically, static virtual methods declare that an implementation must define a set of overloaded operators.

However, override keyword is not applied. It can be seen at this tutorial about static abstract interface methods.

why is that that we are not OBLIGED to use the override keyword

Because we are not overridig behavior, we are replacing behavior. I mean that we cannot call base keyword on concrete implementations of interfaces. It is like using new keyword instead of override

  • Related