Default implementations in Interfaces C# 8.0

Default implementations in Interfaces C 80

In this article, we shall see the default Interface implementation feature made available in the recent C# 8.0 language version.

This feature will be available across .NET ecosystem i.e .NET Core, .NET and .NET Standards framework.

Before you could use these feature please make sure, you have a few prerequisites in place.

Today in this article, we will cover below aspects,

Interface can not have implementation ?

We all understand this old definition of Interface that its members can not have the implementation. A common interview question..isn’t it?

But with C# 8.0 version this decade-old definition has now changed. Now interface can also have implementation defined. So please be acknowledged of this update. Especially when you attend the interview or have a privilege of interviewing someone );

Getting Started

Here below is Interface IFeature,

interface IFeature
    {
        void FeatureJanuary(string featureName);
    }

Here below is class FeatureA which implements the Interface IFeature and provides its own implementation for the method FeatureJanuary(..).

class FeatureA : IFeature
    {
        public void FeatureJanuary(string featureName)
        {
            // Method intentionally left empty.
            Console.WriteLine("FeatureA invoked");
        }
    }

Let’s now add a default implementation to the original contract. The good thing is this new method implementation won’t break any existing client.

interface IFeature
    {
        void FeatureJanuary(string featureName);
        void FeatureFebruary(string featureName)
        {
            Console.WriteLine("FeatureFebruary invoked");

        }
    }

Finally, the client code can call default implementation easily as below.

This gives an additional capability one can add to an existing interface without breaking any implementor of the Interface. It’s very much safe to do so.

Default implementations in Interfaces C 80

I found Interface’s definition now close to that of Abstract Classes where Abstract class has its own implementation and at the same time derived class has a choice to either use an existing abstract method or override those methods with its own implementation.

References:

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *