C# 8.0 New Feature–Interface Default Implementation for Methods

With upcoming C# 8.0, there is an interesting feature called default implementation body for methods within an interface definition. That means if you have few methods signatures defined and you want make implementation classes to implement these methods optionally (remember, previously all interface methods needs to be implemented in implementation classes) , with C# 8.0, you can define methods to follow default implementation body, if it not explicitly implemented by implementation classes of the same interface.

When will we get C# 8.0?

C# 8.0 will be released along .NET Core 3.0, in upcoming months. Currently preview 1 version is available to try out.

Get Started:

1.) First of all, download and install Preview 1 of .NET Core 3.0 and Preview 1 of Visual Studio 2019.

imageimage

image

2.) Launch Visual Studio 2019 Preview, Create a new project, and select “Console App (.NET Core)” as the project type.

image

image

image

3.) Once the project is up and running, change its target framework to .NET Core 3.0 (right click the project in Solution Explorer, select Properties and use the drop down menu on the Application tab).

image

Here is how it can be implemented:

using System;

namespace CSharp8Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            IVehicle bmw = new Bmw();
            bmw.DefaultMessage();

            IVehicle audi = new Audi();
            audi.DefaultMessage(); 
        }
    }


    interface IVehicle
    {
        //default implementation 
        void DisplayMessage();

        void DefaultMessage() { Console.WriteLine("I am  inside default method in the interface!");} 
      
    }

    public class Bmw : IVehicle
    {
        public void DisplayMessage()
        {
            Console.WriteLine("I am BMW!!!");
        }
    }

    public class Audi : IVehicle
    {
        public void DisplayMessage()
        {
            Console.WriteLine("I am AUDI!!!");
        }
        public void DefaultMessage() => Console.WriteLine("I am  inside audi class!");
    }
}