In my previous post, I have explained about one of the first four features of C# 8.0 which has been announced by Microsoft recently.

In this post, I will explain one more future feature which is Default Interface Methods.

This feature will allow interfaces to fully define methods just like abstract classes. However, interfaces will still not be able to declare constructors or fields.

Let us see what it is:

Let us take one example of an interface, like IMessage and it has one method named Message as shown below:

interface IMessage { void Message(); }

And a class will implement it as below:

Class Test : IMessage { }

Now imagine we want to add a new method to the interface, it will result in lots of errors in all the classes which have inherited IMessage interface.

Here comes the new feature which changes some basic functionalities of C# language.

We will create a method with the implementation in the interface. Yes, you read it right, we will be able to write the implementation of the method into the interface as below:

interface IMessage { void Message(); void MessageAll(IEnumberable<MyClass> myClass){ foreach(var i in myClass) { //// Your code } } }

So no need to write newly added method into all the classes which inherit IMessage interface.

It is cool, isn’t it?

One basic question would come in the mind is, what is the difference between this and the abstract class?

They are bit similar but there are some major differences.

One of the difference is:

The interface can be used for multiple inheritances but Abstract class can not be used

Interfaces will still not be able to declare constructors or fields.

Some useful points for Default Methods feature:

“Full abstraction” where we used to have plain interfaces and all classes were forced to have its own implementation. Now we are polluting classes with some default implementation for methods which they don’t even know those exist.

It also breaks interface segregation principle, if we have to change an interface in future and it should not break all the classes but some of the classes need to have the new method added means, the interface is not granular enough and it’s time to introduce new interface and implement for the required classes.

Java announced almost similar feature with 8.0 version earlier and it is becoming so famous among Java developers and it will soon become famous between .Net developers as well 🙂