How to use default interface methods in C# 8.0

Take advantage of default interface methods in C# 8.0 to add new methods to an interface without breaking existing implementations

How to use default interface methods in C# 8.0
Dean Mitchell / Getty Images

One of the new and interesting features in C# 8.0 is the support for default interface methods (also known as virtual extension methods). This article presents a discussion of default interface methods and how we can work with them in C# 8.0.

Until C# 8.0, an interface in C# could not contain method definitions. You could only include method declarations in an interface, and the members of an interface were public and abstract by default. Further, until C# 8.0, an interface could not contain fields, nor could it have private, protected, or internal members. If you introduced a new member (i.e., a method declaration) in an interface, all of your classes that implement the interface would have to be updated.

With C# 8.0, you can now have default implementations of methods in an interface. Interface members can be private, protected, and static as well. Protected members of an interface cannot be accessed in the class that extends the interface. Rather, they can be accessed only in the derived interface. Interface members can also be virtual and abstract. However, virtual members of an interface can be overridden by the derived interface but not by a class that extends the interface. Note that you still can’t include an instance member in an interface.

Why use default interface methods?

Default interface methods are methods in an interface that contain concrete implementations. If the class that extends the interface doesn’t implement the method, the default implementation of the method will be used from the interface. This is a useful feature as it helps developers add methods to future versions of an interface without breaking the existing functionality, i.e., the existing implementations of that interface.

To continue reading this article register now

How to choose a low-code development platform