Home > other >  Abstract modifier on interface method
Abstract modifier on interface method

Time:09-08

Today I was copying some methods from an abstract class to an Interface and I realized that the compiler does not underline the abstract keyword. I tried to look up the documentation but found nothing about it.

I also put it into SharpLab but see no difference between the two.

public interface ITestAbstract
{
    public abstract void MyTest();
}

public interface ITest
{
    public void MyTest();
}

My guess is, that it is allowed since, by default interface methods are actually abstract methods, or am I missing something out?

CodePudding user response:

This feature was added in C# 8 - Default Interface Methods:

Modifiers in interfaces

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.

This means that you are not allowed to modify your methods with abstract before this.

One of the purposes is to support reabstraction. Example from the docs:

interface IA
{
    void M() { WriteLine("IA.M"); }
}
interface IB : IA
{
    abstract void IA.M();
}
class C : IB { } // error: class 'C' does not implement 'IA.M'.
  • Related