Search code examples
c#.netc#-8.0default-interface-member

abstract, virtual and sealed methods in interfaces of C# 8


The following interface has no errors in a .NET Core Console application with C# 8.0

interface I
{
    public abstract void f();
    public virtual void g() => Console.WriteLine("g");
    public sealed void h() => Console.WriteLine("h");
}

abstract prevents adding a definition in interface. virtual and sealed necessitate a definition in interface. sealed prevents an implementation of h in derived classes.

Do abstract, virtual and sealed, when used in interfaces, have any other meaning or applications in current implemented version of C# 8? How and when should they be used in interfaces?


Solution

  • This is from the proposal:

    The syntax for an interface is relaxed to permit modifiers on its members. The following are permitted: private, protected, internal, public, virtual, abstract, sealed, static, extern, and partial.

    An interface member whose declaration includes a body is a virtual member unless the sealed or private modifier is used. The virtual modifier may be used on a function member that would otherwise be implicitly virtual. Similarly, although abstract is the default on interface members without bodies, that modifier may be given explicitly. A non-virtual member may be declared using the sealed keyword.

    It is an error for a private or sealed function member of an interface to have no body. A private function member may not have the modifier sealed.