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