Home > Software design >  What is the difference between declaring an abstract function within an interface and declaring a fu
What is the difference between declaring an abstract function within an interface and declaring a fu

Time:07-31

I have a question while studying C#. When I declare the interface, I usually declare it like the code below

public interface IRequireInitialization
{
    void Init();
}
public class TESTManager : IRequireInitialization
{
    public void Init(){ throw new NotImplementedException(); }
}

but my friend said that I should add abstract before the declaration of the interface member function. I didn't feel any big difference in implementing the interface, what's the difference? And if there is a difference, when should I use it?

public interface IRequireInitialization
{
    abstract void Init();
}
public class TESTManager : IRequireInitialization
{
    public void Init(){ throw new NotImplementedException(); }
}

CodePudding user response:

C# 8 introduced default interface methods. This allows to define a default implementation (body) for a method in the interface itself.

As part of this proposal they relaxed the syntax to allow modifiers for interface methods:

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.

A method in an interface is abstract by default and abstract modified just makes that explicit:

similarly, although abstract is the default on interface members without bodies, that modifier may be given explicitly.

  • Related