Introduction
We never had a provision to define method body in C# interfaces, but C# 8.0 brings you the ability to define method body into your interface. In C# 8 on .NET Core 3.0, you can define an implementation to an interface. The main scenario is to add new members to an existing interface which is already in production.
Let's see how the old C# interface used to be before this feature.
- public class Training
- {
- public Training(string name, string cost)
- {
- Name = name;
- Cost = cost;
- }
- public string Name { get; set; }
- public string Cost { get; set; }
- }
- interface ITrainingService
- {
- IList<Training> Trainings { get; }
- void AddTraining(string name, string cost);
- void AddTraining(Training training);
- }
Here, we have two interface methods which you are forced to implement in your derived classes, but in C# 8.0, you can define method implementation directly inside interface which allows you to write less code during implementation and common code of different derived classes can be written directly in the interface, an alternate of abstract class.
In this example, if you want to add a training object which is going to common by adding a name, cost or by training object. If more than one class is implementing this interface, you have to write the same implementation either by creating a base abstract class or possibly in both derived classes. Now, you can use this new C# 8.0 feature and write the kind of common implementation directly in the interface.
Upgrade default interface methods

DeepikaPosted Dec 19, 2019, 11:54 AM
Thanks for letting us know abt new feature of c#, i have started following you to get new on c# and Microsoft technology. thanks again
AnandPosted Dec 19, 2019, 11:50 AM
Great to know this..i was not aware of this feature. thanks for letting us know.
Sourav Kumar DasPosted Dec 19, 2019, 5:09 AM
Nice and useful article.
Rushi MehtaPosted Dec 19, 2019, 4:07 AM
Great stuff for learning