Default Interface Methods in C#


Default interface methods are a game-changing feature that allow developers to add new methods to an interface without breaking existing implementations. This article will explain default interface methods in C#, showing you how to use them effectively in your own code.

Traditional Interface Methods in C#

Traditionally, interfaces in C# could only contain declarations of methods, properties, events, or indexers, but not their implementations. Any class or struct that implemented the interface had to provide the implementation for each member of the interface.

Introduction to Default Interface Methods

Default interface methods were introduced to address the limitation of traditional interfaces. With default interface methods, you can provide a default implementation for a method directly in an interface. If a class or struct implements the interface but does not provide an implementation for this method, the default implementation will be used.

Here's a simple example −

public interface IGreetable {
   void Greet(string name) {
      Console.WriteLine($"Hello, {name}!");
   }
}

public class User : IGreetable {
   // No need to implement Greet method, the default implementation will be used.
}

Note − Default interface methods were part of the proposed features for C# 8.0.

In this example, the IGreetable interface has a default implementation for the Greet method. The User class implements IGreetable but does not provide its own implementation for Greet, so the default implementation will be used.

Overriding Default Interface Methods

Even though an interface provides a default implementation for a method, an implementing class or struct can still provide its own implementation. This is called overriding the default implementation.

public class Admin : IGreetable {
   public void Greet(string name) {
      Console.WriteLine($"Hello, {name}. You are an admin.");
   }
}

In this example, the Admin class provides its own implementation for the Greet method, overriding the default implementation provided by IGreetable.

Conclusion

Default interface methods are a powerful feature in C# that allow you to evolve interfaces over time without breaking existing implementations. By understanding default interface methods, you can create more flexible and adaptable code in C#.

Updated on: 24-Jul-2023

298 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements