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 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