Saturday, October 26, 2019

C# 8.0: Default Implementations of Interface Members

C# 8.0 has introduced some great features to the language and one of them is being able to have default implementations for Interface members. A couple of other features are also introduced to Interfaces to support and enhance this feature.

In this post, let's see have a look at what this really is. And to try this out, you’ll need to set up your machine to run .NET Core, including the C# 8.0 compiler. The C# 8.0 compiler is available starting with Visual Studio 2019 version 16.3 or the .NET Core 3.0 SDK.

Up to C# 8.0, this is what we know of Interfaces in .NET.
  • Interface members cannot have a definition / cannot have implementations
  • Interfaces cannot contain fields
  • For interface member declarations, only the new modifier is valid, you can't have any other modifiers like public, protected, private, etc.
  • All the interfaces members are by default, public and abstract
But with C# 8.0, whole a lot of things have changed. The main thing is Interface members can now have a default implementation.

Previously if you add a new method to an interface, all of your classes implementing that interface need to implement that method. Otherwise, it's going throw compile-time errors in the related classes. We all know that is a huge pain. How about being able to define a default implementation in the interface itself and let your classes override whenever they wish to. This is exactly what this feature is all about.

Consider the below code.
public interface IMyInterface
{
    void MyFirstMethod()
    {
        throw new NotImplementedException();
    }
}
 
public class MyFirstClass : IMyInterface
{
    public void MyFirstMethod()
    {
        Console.WriteLine("Hello World");
    }
}
 
public class MySecondClass : IMyInterface { }
So above is not possible prior to C# 8.0, but perfectly valid with C# 8.0. Note: that a class does not inherit members from its interfaces; that is not changed by this feature. So this is not possible.
new MySecondClass().MyFirstMethod();
So along with this, the following are also possible.
  • An interface can have static fields, but not instance fields
  • Interfaces can now have private members
  • Interfaces can now also have static members. This is used for parameterization of the default implementation.
  • Interfaces can also have protected members. They are not accessible by the derived class but via the derived interface.
  • Interfaces can also have virtual members, but the class can’t override the method. An interface can only override it.

Isn't this great!

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment