Saturday, June 27, 2026

C# Understanding Default Interface Method in Interface type and how to call it

In this post, you will understand about default interface method in an interface type. For this, look at the following code and answer this question: How to call default interface method Print of IContract interface in Program class?
interface IContract
{
    void Apply();
    void Print()
    {
        Console.WriteLine("Print Default implementation");
    }
}
class Implementer : IContract
{
    public void Apply()
    {
        Console.WriteLine("Implementer implemented Apply");
    }
    public void Print()
    {
        Console.WriteLine("Implementer implemented Print");
    }

    class Program
    {
        static void Main(string[] args)
        {
            Implementer implementer = new Implementer();
            implementer.Apply(); // Implementer implemented Apply
            implementer.Print(); // Implementer implemented Print
            IContract contract = implementer;
            contract.Print(); // Implementer implemented Print
        }
    }
}
Answer: Since default interface method Print is implemented in Implementer class, calling Print will invoke class implementation, not interface implementation. If you really want to invoke interface method implementation then class should not re-implement the default interface method implementation.
Soultion:
interface IContract
{
    void Apply();
    void Print()
    {
        Console.WriteLine("Print Default implementation");
    }
}
class Implementer : IContract
{
    public void Apply()
    {
        Console.WriteLine("Implementer implemented Apply");
    }

    class Program
    {
        static void Main(string[] args)
        {
            Implementer implementer = new Implementer();
            implementer.Apply(); // Implementer implemented Apply
            IContract contract = implementer;
            contract.Print(); // Print Default implementation
        }
    }
}
Since C# version 8 onward, method implementation is allowed in an interface type. The class implementing this interface cannot directly access this method. It means that class reference variable cannot directly acces this method.
implementer.Print(); // Invalid access

The compiler message is: "'Implementer' does not contain a definition for 'Print' and no accessible extension method 'Print' accepting a first argument of type 'Implementer' could be found (are you missing a using directive or an assembly reference?)"

But the interface reference variable pointing to the object of implementing class can access this method.
contract.Print(); // Print Default implementation

No comments:

Post a Comment

Hot Topics