Default Interface Methods in C# 8.0
Background
We have been using the interfaces for years and we know that interfaces are just contracts and class that inherits them must implement all methods of interface.
public interface INewsletter
{
void WriteFirstNewsletter();
}
public class Newsletter : INewsletter
{
public void WriteFirstNewsletter()
{
Console.WriteLine("I am first Newsletter");
}
}
Default Interface
Suppose this Interface is being implemented by multiple classes 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 default implementation of methods and it will not break all those classes that are implementing the interface.
public interface INewsletter
{
void WriteFirstNewsletter();
void WriteLastNewsletter()
{
Console.WriteLine("I am last Newsletter {By Default}");
}
}
public class Newsletter : INewsletter
{
public void WriteFirstNewsletter()
{
Console.WriteLine("I am first Newsletter");
}
}
Benefits
So what are the benefits of using it
-
Without breaking default implementation we can add new methods now in interface , but we can do this through extension method as well ( creating an extension method for your interface).
-
Class implementing interface is not aware about default implementation of method.
-
Most importantly default interface methods can avoid diamond problem
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place