Skip to main content
Interface method implementation C# 8.0

Interface Method Implementation C# 8.0

In our previous post, we have tried to provide an overview of first four features of C# 8.0 which has been announced by Microsoft recently.

In this post, we will explain one of those four features in detail which is Default Interface.

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.

Interface method implementation C# 8.0

Let us take one example of an interface, like 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 IEmail interface.

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

We will create a method with 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<MyClass>)
    { 
        foreach(var e in myClass) 
        { 
            //// Your code 
        } 
    }
}

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

It is cool, isn’t it?

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

They are bit similar but there are some major differences.

  • The interface can be used for multiple inheritance 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.

Happy Coding!

Was this article worth reading? Share it with fellow developers too.

DotNetCrunch

DotNetCrunch is a popular blog for latest Microsoft® technologies which is aimed for beginners and intermediate level professionals.