Click here to Skip to main content
15,880,503 members
Articles / Programming Languages / C#

C# 8 Interfaces

Rate me:
Please Sign up or sign in to vote.
3.58/5 (16 votes)
2 Jul 2019CPOL5 min read 14.6K   4   6
C# 8.0 Interface and default methods

Introduction

As we all know, C# 8.0 was released few days ago. Many exciting features have come up with this release of C#. Significant amount of changes in interfaces have also happened, so with this article, let’s try to explore the new features and try to learn how we can use them in the projects. The agenda for this article will be as listed below:

Interfaces Today

As a developer, we all make use of the interface, be it to create the loosely coupled component or to define the contract which should be implemented by concrete class. Today’s interfaces never come up with the body, no modifiers. It is the responsibility of the implementer class to provide body and assign some modifiers to it. If the class does not implement the method, the compiler catches it and gives the error saying we need to implement the interface.

Throughout this application, we will use the example of the Logger class and make changes accordingly.

C#
using System;
public interface ILogger
{
void Log(string Info);
}
public class TextLogger : ILogger
{
 public void Log(string Info)=> Console.Write("In base Logger");
}

We have defined one interface called ILogger with one method Log(). We have a class called TextLogger which is implementing the interface ILogger. This is perfectly fine considering the current state of the design. Now, the problem occurs when we want to extend the ILogger and need to add some more information in it like below:

C#
public interface ILogger
{
void Log(string info);
void Log(string typeofInformation,string info)
}

Now we will have an issue here as this new method must be implemented by the class where this interface is used and the compiler will show us an error until this is done like below:

Image 1

Now considering this interface is being used by multiple classes, this will break many changes and it will be really painful to make these changes across the implementation depending on the places where this interface is used. We need to implement this method across so as to make our code compile. In order to overcome this, C# 8 came up with the idea of the Default Methods in interfaces.

Default Interface Methods

The main reason to get this feature in C# 8.0 is to provide the default implementation for the interface methods so how can we do this? Let's see the following example:

C#
using System; 
public interface ILogger
{ void Log(string info); 
//Default implementation void LogInfo(string typeofInformation,
//string info)=>Console.Write(typeofInformation+ " " + info); 
}
public class TextLogger : ILogger { 
public void Log(string info)=> Console.Write("In base Logger"); 
}

Here, we can see in the interface itself, we have provided the implementation for the function. Here, our Class TextLogger does not need to implement this method and there will not be any compile time error. Now in order to use this interface in our application, let's change our main method and let's see how we can use it.

C#
class Program
    {
        static void Main(string[] args)
        {
           ILogger _logger = new TextLogger();
           _logger.LogInfo("Test","test"); // It will call the Default method of the interface
        }  
      }}

One more thing that we need to check is that Default methods will only work if the class is contextually treated as interfaces. If we are not doing that, then the default method implementation will not be available for use:

Image 2

In the above screenshot, we can see while creating the object from class, we can see the default method is not available to use. If we look at this feature closely, we can see that this can lead to the very well-known problem of Multiple Inheritance which is famously called as the Diamond Problem. By design, C# won’t face any issues as Multiple inheritance is not possible with the classes and interfaces don't have implementation of the methods but with the default method, this is going to change. Let’s see how it will be handled in C# 8.0.

Diamond Problem

Diamond problem is one of the big issues in languages as C# classes do not support this feature which is a result of multiple inheritance, but interfaces can introduce this problem up to some extent. Let’s see how C# handles them. The following diagram illustrates what the diamond problem is:

Image 3

The above figure depicts the Diamond problem very well. Now, let’s see with the default interfaces how this problem can arise and how C# handles it. Let’s design the interfaces like below:

C#
Interface First
{
    void WritetoConsole() => Console.Write("In First");
}

interface Second:First{
 void First.WritetoConsole()=>Console.Write("In Second");
}

interface Third:First{
  void First.WritetoConsole()=>Console.Write("In Third");
}

class FinalClass : Second,Third
{
}

On writing this code, we will have the compile time error:

Image 4

Error message will be Interface member 'First.WritetoConsole()' does not have a most specific implementation. Neither 'Second.First.WritetoConsole()', nor 'Third.First.WritetoConsole()' are most specific. (CS8705) [DefaultInterfaceDemo]. In order to solve this problem as depicted in the Error itself, we need to provide the most specific override at the time at the time of execution, Dotnet design team has told specifically about it as follows, “A class implementation of an interface member should always win over a default implementation in an interface, even if it is inherited from a base class. Default implementations are always a fall back only for when the class does not have any implementation of the member at all.” Let’s see how we can provide the default implementation and solve this diamond problem.

C#
using System;
interface First
{
    void WritetoConsole() => Console.Write("In First");
}

interface Second:First{
 void First.WritetoConsole()=>Console.Write("In Second");
}

interface Third:First{
  void First.WritetoConsole()=>Console.Write("In Third");
}

class FinalClass : Second,Third
{
  void First.WritetoConsole(){
  Console.Write("From Final class");
}
}

Modifiers in Interfaces

Traditionally till the arrival of C# 8.0, we could not use the modifiers in the interfaces. With C# 8.0, we can use them, till now modifiers like private, protected, internal, public and virtual are allowed. By design, all the default interface methods are made virtual unless we are making them private or sealed. All the members without body are treated as abstract by default making it compulsory to be implemented in the concrete classes.

C#
using System;
interface IInterfaceModifiers
{
  //By Default default method is private
  virtual void DefaultMethod()=>Console.WriteLine("Default method");
  //Private Default Method
  private void privatedefaultmethod()=>Console.WriteLine(" private Default method");
  //Protected Default Method
  protected void ProtectedDefaultMethod()=>Console.WriteLine(" protected Default method");
  // Public Default Method
  public void PublicDefaultMethod()=>Console.WriteLine(" public Default method");
  virtual void VirtualDefaultMethod()=>Console.WriteLine("Virtual Default method");
  abstract void AbstractDefaultMethod();
}
<hr>
class InterfaceModifierDemo : IInterfaceModifiers
{  
  public void AbstractDefaultMethod() => Console.WriteLine("Abstract virtual method");}

namespace DeaultInterfaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            IInterfaceModifiers i= new InterfaceModifierDemo();
            i.AbstractDefaultMethod();
            i.DefaultMethod();
            i.PublicDefaultMethod();
            i.VirtualDefaultMethod();
        }
    }
}

When we run the above code, we can see the following output on the console:

Abstract virtual method
Default method
public Default method
Virtual Default method

Apart from this, few observations that I come across in this example. When we make a method virtual, we can override that method in the interface itself and we cannot override it in the implementation class. When we make one method protected, it is available in the inheriting interface rather than implementing class. By default, the members of the interfaces are abstract which makes it compulsory for the implementing class to implement them properly.

Summary

We have seen the most controversial yet most exciting feature of C#8.0. It will change the way we have been using the interfaces in the design, which will certainly help developers in producing less breaking changes, but also it will come up with its own challenges of performance and design perspectives. Another thing to add is this feature will not be available in the .NET Framework for now but included in the .NET Core and Core CLR as well as MONO.

References

History

  • 2nd July, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionChanging interfaces is a questionable practice Pin
James Lonero4-Jul-19 11:28
James Lonero4-Jul-19 11:28 
AnswerRe: Changing interfaces is a questionable practice Pin
Mangesh_Gaherwar4-Jul-19 16:45
Mangesh_Gaherwar4-Jul-19 16:45 
QuestionWhy changing an existing interface? Pin
PaulNijssen3-Jul-19 22:08
PaulNijssen3-Jul-19 22:08 
AnswerRe: Why changing an existing interface? Pin
Mangesh_Gaherwar4-Jul-19 16:50
Mangesh_Gaherwar4-Jul-19 16:50 
GeneralMy vote of 5 Pin
Hyland Computer Systems3-Jul-19 16:44
Hyland Computer Systems3-Jul-19 16:44 
Thanks for this very concise, informative definition of C# 8.0's new Interfaces.
GeneralMy vote of 5 Pin
tal_segal3-Jul-19 3:34
tal_segal3-Jul-19 3:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.