Interfaces can have private methods

10/25/2023
1 minute read

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 useful extensions for IEnumerable

I did already write about some useful extension methods for Task and ValueTask. Today I want to show you some useful extension methods for IEnumerable.

Abstract class vs interface

In C# we have abstract classes and we also have interfaces. Both seem very similiar but they are fundamentally different concepts.

Therefore let's discover what the difference is, what the overlap is and when to use what.

static abstract interfaces and generic math

Besides the big announcements of .NET 6 there are also some smaller features. I want to show case a special one: static abstract interfaces. With this you have ability to extend the contract in that sense, that an implementing class has to provide also static methods. This feature is right now flagged as preview, but you can use it if you want.

This also enables generic math operations on an interface level.

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