The output is Bar-Bar-Quux as a result of 3 calls to GetName() in your Console.WriteLine method call.
Bar f1 = new Baz();
IFoo f2 = new Baz();
IFoo f3 = new Quux();
Console.WriteLine(f1.GetName() + "-" + f2.GetName() + "-" + f3.GetName());
//Bar-Bar-Quux
Let's examine each call so it can be made more clear what happens.
f1.GetName()
f1
is instantiated as Baz
. However, it is typed as Bar
. Because Bar
exposes GetName
, when f1.GetName()
is used, that is the method which is called - regardless of the fact that Baz
also implements GetName
. The reason is that f1
is not typed as Baz
, and if it were, it would call Baz
's GetName
method. An example of that would be to examine the output of
Console.WriteLine(((Baz)f1).GetName() + "-" + f2.GetName() + "-" + f3.GetName());
//Baz-Bar-Quux
This is possible because of two facts. First, f1
was initially instantiated as Baz
, it was simply typed as Bar
. Second, Baz
does have a GetName
method, and the use of new
in its definition hides the inherited Bar
's GetName
method allowing Baz
's GetName
to be called.
f2.GetName()
A very similar typing is occurring with f2
, which is defined as
IFoo f2 = new Baz();
While the Baz class does implement a GetName
method, it does not implement IFoo
's GetName
method because Baz
does not inherit from IFoo
and therefore the method is not available. Bar
implements IFoo
, and since Baz
inherits from Bar
, Bar
's GetName
is the method which is exposed when f2
is typed as IFoo
.
Again, since f2
was initially instantiated as Baz
, it can still be cast to Baz
.
Console.WriteLine(f1.GetName() + "-" + ((Baz)f2).GetName() + "-" + f3.GetName());
//Bar-Baz-Quux
And will have the same output result for the reason noted above for f1
(f2
was originally typed as Baz
, and Baz
's GetName
method hides the inherited Bar
's GetName
method).
f3.GetName()
Different story here. Quux
does inherit and implement IFoo
, and it hides Bar
's implementation of IFoo
by using new
. The result is that Quux
's GetName
method is the one which is called.
Baz
is not implementingIFoo
. Removed comment. – CastanoBaz
does implementIFoo
through its inheritance ofBar
. – Multiple