Default interface methods are a game-changing feature that allows developers to add new methods to an interface without breaking existing implementations. This article explains default interface methods in C# and shows you how to use them effectively in your own code.
Traditionally, interfaces in C# can only contain declarations of methods, properties, events, or indexers, but not their implementations. Any class or structure that implements this interface must provide an implementation for each member of the interface.
Default interface methods were introduced to solve the limitations of traditional interfaces. Default interface methods allow you to provide a default implementation for a method directly in the interface. If a class or struct implements the interface but does not provide an implementation for the method, the default implementation will be used.
This is 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 are part of the proposed functionality of C# 8.0.
In this example, the IGreetable interface has a default implementation of the Greet method. The User class implements IGreetable but does not provide its own Greet implementation, so the default implementation will be used.
Even if an interface provides a default implementation for a method, an implementing class or structure 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.
Default interface methods are a powerful feature in C# that allow you to improve the interface over time without breaking the existing implementation. By understanding default interface methods, you can create more flexible and adaptable code in C#.
The above is the detailed content of Default interface methods in C#. For more information, please follow other related articles on the PHP Chinese website!