Saturday, August 29, 2026

C# Default Method implementation in interface

Since C#8, you can define a method with its implementation in interface. The question is: when can you use this default implementation. The answer is : you can use default implementation as long as re-implementation of method doesn't exist in the implementing class of the interface. If a re-implementation exists, the default method implementation is never used; it becomes useless. So, defining a default method implementation in interface makes sense if you want a uniform method definition for all the classes that implement the interface. They will have a common method definition, if interface defines a method.

Look at the following code.

namespace Practicals
{
    interface IMyInterface
    {
        void DoSomething()
        {
            Console.WriteLine("Default implementation");
        }
    }

    class MyClass : IMyInterface
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass obj = new MyClass();

            IMyInterface iobj = obj;
            iobj.DoSomething(); // Default implementation
        }
    }
}
The output is: Default implementation
What if the MyClass re-implements the DoSomething method?

namespace Practicals
{
    interface IMyInterface
    {
        void DoSomething()
        {
            Console.WriteLine("Default implementation");
        }
    }

    class MyClass : IMyInterface
    {
        public void DoSomething()
        {
            Console.WriteLine("Re implementation");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass obj = new MyClass();
            obj.DoSomething(); // Re implementation
            IMyInterface iobj = obj;
            iobj.DoSomething(); // Re implementation
        }
    }
}

The output is: Re implementation

The default implementation of interface is never used if a re-implementation exists in the implementing class. No matter you call using a reference variable of implementing class or interface, the default implementation of interface is never; the re-implementation of interface is used.

No comments:

Post a Comment

Hot Topics