Default Interface Methods

We have been using the interfaces for years and know that interfaces are just contracts and the class that inherits them must implement all methods of an interface.

public interface IFeatureOfInterface
{
        public void WriteFeature();
}

public class Feature:IFeatureOfInterface
{
        public void WriteFeature()
        {
                Console.WriteLine("Default Interface Methods in C# 8.0");
        }
}

Suppose multiple classes are implementing this Interface, and now you want to add some more methods in that interface.

  • If we talk about the time before C# 8.0, then you can not do this because it will break all classes implementing that interface, and you must implement that method.
  • But with C# 8.0 now, we can add the default implementation of methods, and it will not break all those classes implementing the interface.
public interface IFeatureOfInterface
{
        public void WriteFeature();
        public void DefaultFeature()
        {
            Console.WriteLine("Default Feature");    
        }
}

public class Feature: IFeatureOfInterface
{
        public void WriteFeature()
        {
                Console.WriteLine("Default Interface Methods in C# 8.0");
        }
}

So, what are the benefits of using it?

  1. Without breaking the default implementation, we can add new methods in the interface, but we can do this through an extension method as well ( creating an extension method for your interface).
  2. The class implementing the interface is not aware of the default implementation of the method.
  3. Most importantly, default interface methods can avoid the diamond problem