DEV Community

Cover image for C# - Default Interface Methods
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Default Interface Methods

Default interface methods are a feature in C# that allows you to define an implementation for an interface member. This can provide a lot of flexibility, especially when evolving interfaces over time without breaking existing implementations.

For instance, you might have an interface representing a sensor in an IoT application, and over time you want to add a new method to it. Adding a new method to the interface would break all existing implementations. With default interface methods, you can add a new method with a default implementation, and all the existing implementations will continue to work without any modifications.

Here's an example of how to use default interface methods:

public interface ISensor
{
    string GetStatus();

    // New method with a default implementation
    void Reset()
    {
        Console.WriteLine("Default reset implementation.");
    }
}

public class TemperatureSensor : ISensor
{
    public string GetStatus()
    {
        // Implementation specific to temperature sensor.
        return "TemperatureSensor status";
    }

    // Reset method isn't required to be implemented thanks to the default implementation.
}

public class Program
{
    public static void Main()
    {
        ISensor sensor = new TemperatureSensor();
        Console.WriteLine(sensor.GetStatus()); // Output: TemperatureSensor status
        sensor.Reset(); // Output: Default reset implementation.
    }
}
Enter fullscreen mode Exit fullscreen mode

Use default interface methods to add new functionality to interfaces while keeping backward compatibility with classes that were written against earlier versions of the interface. This allows for more flexible and robust API design, particularly in libraries and frameworks.

Top comments (0)