Default Interface Methods in C#

An Interface in C# programming language is defined as an abstract type used to specify the behavior of a class. An interface in C# is a blueprint of a class. A C# interface contains static constants and abstract methods.

The interface in C# is a mechanism to achieve abstraction. There can be only abstract methods in the C# interface, not the method body. It is used to achieve abstraction and multiple inheritance in C#. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

Today, I saw a question on StackOverflow related to interfaces in C#. Someone asked "How to use default interface methods in specific class". As shown in the following snapshot, we can see that there some methods with concrete implementation in both interfaces IPrinter and IScanner. 

How to use default interface methods in specific class?

Default Interface Methods in C#

You may wonder if it is possible to have default methods in an Interface with concrete implementation. Well, starting with C# 8.0, an interface may define a default implementation for members, this wasn't possible before. Technically they are called "Default interface methods"

You can check the following references to learn more about the default methods in C# interface:

  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods

  • https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/default-interface-methods-versions

Post a Comment

Previous Post Next Post