The following code gives different outputs. Can anyone explain why?
The code is displayed below. The result set is shown underneath it.
I have compiled the code on Enterprise VS 2015, Update 2.
I run it on Win7.
Please notice that I am using shadowing (hiding) in both examples. This question doesn't concern the use of shadowing vs overriding. The question asks "Why does shadowing result in two different outputs?"
Here is the code that compiles and runs and gives different results for the two different methods of calling the objects:
using System;
namespace InheritanceApplication
{
internal class FooBarParent
{
public void Display()
{
Console.WriteLine("FooBarParent::Display");
}
}
internal class FooBarSon : FooBarParent
{
public new void Display()
{
Console.WriteLine("FooBarSon::Display");
}
}
internal class FooBarDaughter : FooBarParent
{
public new void Display()
{
Console.WriteLine("FooBarDaughter::Display");
}
}
internal class Example
{
public static void Main()
{
GoodBar();
FooBar();
}
public static void GoodBar()
{
Console.WriteLine("Example::Goodbar ...");
var fooBarParent = new FooBarParent();
fooBarParent.Display();
var fooBarSon = new FooBarSon();
fooBarSon.Display();
var fooBarDaughter = new FooBarDaughter();
fooBarDaughter.Display();
}
public static void FooBar()
{
Console.WriteLine();
Console.WriteLine("Example::Foobar ...");
var fooBarFamily = new FooBarParent();
fooBarFamily.Display();
fooBarFamily = new FooBarSon();
fooBarFamily.Display();
fooBarFamily = new FooBarDaughter();
fooBarFamily.Display();
}
}
}
Here is the result set:
Example::Goodbar ...
FooBarParent::Display
FooBarSon::Display
FooBarDaughter::Display
Example::Foobar ...
FooBarParent::Display
FooBarParent::Display
FooBarParent::Display