In this post, we will explain one of the features of C#8 in detail which is the Default Interface Method.
If you are interested to know the features offered by C# since its initial release until know then you may refer below article.
Topics Covered
Introduction
The Default Interface Method feature will allow interfaces to fully define methods just like abstract classes. However, interfaces will still not be able to declare constructors or fields.
Default Interface Method Implementation
Let us take one example of an interface, like the IEmail and it has one method named Email() as shown below:
interface IEmail { void Email(); }
And a class will implement it as below:
class Employee : IEmail { // some code }
Now, if we want to add a new method to the interface, it will result in lots of errors in all the classes which have inherited the IEmail interface.
The New Feature
Here comes the new feature which changes some basic functionalities of C# language.
We will create a method for the implementation of the interface. Yes, you read it right, we will be able to write the implementation of the method into the interface in C# 8.0 unlike previous versions of C#.
interface IEmail { void Email(); void EmailGroup(IEnumberable) { foreach(var e in myClass) { //// Your code } } }
So no need to write a newly added method into all the classes which inherit the IEmail interface.
Isn’t it cool? Comment below and let us know
Now, after going through the above example, one basic question might come to your mind that what is the difference between an interface and the abstract class? aren’t they appearing same?
Differences Between Interface and Abstract Class
They are a bit similar but there are some major differences.
- The interface can be used for multiple inheritances but an Abstract class can not be used.
- Interfaces will still not be able to declare constructors or fields.
This feature already is available in Java 8.0 and it’s very famous among Java developers.
We hope that we have explained the Default Interface Method feature of C#8.0 in a simplified way.
What do you think?
Dear Readers,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.
Happy Coding!