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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay