Interfaces can have private methods

25/10/2023
C#.NET

Let's drop some "useless" knowledge here. Interfaces can have private methods. This comes with the C# 8 feature: "Default interface methods".

Default interface methods allow us to define a default implementation for a method in an interface. This is useful when we want to add a new method to an interface, but we don't want to break all the classes that implement that interface. Something like that:

public interface IMyInterface
{
    public void MyMethod()
    {
        // Do something
    }
}

public class MyClass : IMyInterface
{
    // I don't need to implement MyMethod
}

But when using it, we can't call MyMethod from MyClass:

var myClass = new MyClass();
myClass.MyMethod(); // This won't compile

IMyInterface myInterface = myClass;
myInterface.MyMethod(); // This will compile

And to make that mess a bit messier, we can also refactor out things that are private inside the interface:

public interface IMyInterface
{
    public void MyMethod()
    {
        MyPrivateMethod();
    }

    private void MyPrivateMethod()
    {
        // Do something
    }
}

I am not the biggest fan of this feature, but it's there, and it's good to know about it.

6
An error has occurred. This application may no longer respond until reloaded. Reload x