Your code will have the same output no matter how things work. I suggest using next for clearer understanding:
class Something : ISomething
{
private void DoSomething()
{
Console.WriteLine("Something!");
}
void ISomething.DoSomething()
{
Console.WriteLine("Explicit Something!");
}
};
Which will print Explicit Something!
for your Main
. As for why for both implementations - as draft C# 7.0 specification states:
It is not possible to access an explicit interface member implementation through its qualified interface member name in a method invocation, property access, event access, or indexer access. An explicit interface member implementation can only be accessed through an interface instance, and is in that case referenced simply by its member name.
So DoSomething()
call in original ISomething.DoSomething()
implementation is call to the Something.DoSomething()
and not to ISomething.DoSomething()
. ISomething.DoSomething()
is no accessible cause it requires an interface instance. If you rename ISomething.DoSomething
to for example ISomething.DoSomething1
you will see that it is not accessible inside ISomething.DoSomething1
call unless you cast this
to interface:
interface ISomething
{
void DoSomething1();
}
class Something : ISomething
{
public void DoSomething()
{
Console.WriteLine("Something!");
}
void ISomething.DoSomething1()
{
// DoSomething1(); // The name 'DoSomething1' does not exist in the current context
// ((ISomething)this).DoSomething1(); // will obviously end in SO
Console.WriteLine("ISomething.DoSomething1!");
}
}
Also can be useful interface mapping section:
Notable implications of the interface-mapping algorithm are:
- Explicit interface member implementations take precedence over other members in the same class or struct when determining the class or struct member that implements an interface member.
- Neither non-public nor static members participate in interface mapping.