Introduction
In today’s article we will look at an extremely useful feature introduced with C# 8.0. This is the ability to define default implementations of Interface members. Previously the interface could only define a structure or a method definition, which was then used in the classes that implemented the interface. However, with this new feature we can now add a method definition in the interface itself which will be used when the method is not implemented. How exactly this works is what we will see in this article. C# 8.0 is supported on .NET Core 3.x and .NET Standard 2.1.
Creating Default Implementations of Interface Members
We create a simple .NET core console application using Visual Studio 2019 Community Edition with target framework .NET Core 3.1.
Next, we will create an interface with some members. We also add the default implementation for one of the methods as below:
- public interface IEmployee {
- public int ID {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public double Salary {
- get;
- set;
- }
- public double GetTaxAmount() {
- return Salary * 0.05;
- }
- }
We also create a class which implements this interface but does not implement the one method which has a default implementation:
- public class Employee: IEmployee {
- public Employee(double salary) {
- Salary = salary;
- }
- public int ID {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public double Salary {
- get;
- set;
- }
- }
Using the Default Implementation of the Interface Member
Now, we create an instance of the class into a type of the interface. Then, when we run the code, we see that the default implementation is used as below:
- class Program
- {
- static void Main(string[] args)
- {
- IEmployee employee = new Employee(2500);
- Console.WriteLine($"The Tax amount is {employee.GetTaxAmount()}");
- Console.ReadKey();
- }
- }
Note that if we change the code as below,
- class Program
- {
- static void Main(string[] args)
- {
- Employee employee = new Employee(2500);
- Console.WriteLine($"The Tax amount is {employee.GetTaxAmount()}");
- Console.ReadKey();
- }
- }
We get a compile time error as below:
'Employee' does not contain a definition for 'GetTaxAmount' and no accessible extension method 'GetTaxAmount' accepting a first argument of type 'Employee' could be found (are you missing a using directive or an assembly reference?)
This indicates that we need to define the class instance variable of the interface type as the definition of this method is only in the interface.
Summary
In this article, we looked at how to use default implementations of Interface members in C#. This is just one of the new features that has been introduced in C# 8.0. I will be covering more of these features in future articles. Happy Coding!