Search code examples
c#oopinterfacelanguage-lawyer

What is the rationale of allowing IInterface.Method() and Method() that implements IInterface?


Here's something I do find confusing in C#: the ability to define Method() and IInterface.Method() in a class that implements IInterface.

Example:

public interface ICustomer
{
    void GetName();
}

public class CustomerBase : ICustomer
{
    public void GetName()
    {
        Console.WriteLine("CustomerBase");
    }

    void ICustomer.GetName()
    {
        Console.WriteLine("ICustomer.CustomerBase.GetName()");
    }
}

Yes, GetName() which is a contract method of ICustomer, can coexist with ICustomer.GetName().

Which method is called when? I run the thing in console:

    var customerBase = new CustomerBase();
    customerBase.GetName();  //this prints CustomerBase
    ((ICustomer)customerBase).GetName(); //this prints ICustomer.CustomerBase.GetName()

So, depending on whether customerBase is cast to interface or not, the output is different.

Not only that, the method signature now affects the method that is being called:

    private void PrintCustomer(ICustomer customer)
    {
        customer.GetName();  //this prints ICustomer.CustomerBase.GetName()
    }

    private void PrintCustomer(CustomerBase customer)
    {
        customer.GetName(); //this prints CustomerBase
    }

This behavior is hugely counter-intuitive to me. So here are the questions for the language lawyer:

  1. When this is introduced in C# spec, and at where?
  2. What is the rationale for this? I can't imagine a valid use case, only potential confusion and extra abilities for the developers to shoot themselves in the foot.

Solution

  • So just imagine your class CustomerBase have implemented multiple interfaces like ICustomer, ICustomer1…. and these interfaces have some common methods signatures, let’s say void GetName in your case. In that case how the compiler will determine which method definition is for which interface in your class?