Default implementation of a method for C# interfaces?

C# v8 and above allows concrete implementation for methods in interfaces as well. Earlier it was allowed only for abstract classes.

This change will now shield our concrete classes from side-effects of changing the interface after it has been implemented by a given class e.g. adding a new contract in the interface after the DLL has already been shipped for production use. So our class will still compile properly even after adding a new method signature in the interface being implemented.

This is now possible because we can also provide a default implementation for the new contract being introduced. Thus, we will not have to change any old or existing classes who are using this interface (Refer code snippet).

interface IA
{
    void NotImplementedMethod(); //method having only declaration
    void M() 
    { 
        WriteLine("IA.M"); 
    }//method with declaration + definition
}

In principle, we can say that C# interfaces have now started behaving like abstract classes.

References:

  • MS Docs link – https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods
  • You can refer to the GitHub issue # 288 for implementation details.
  • Also, Mads Torgersen talks about this feature at length in this channel 9 video.

Leave a Comment