I’ve been studying class inheritance recently and I keep coming across this specific piece of code.
public class Foo {
public bool DoSomething()
{
return false;
}
}
public class Bar : Foo {
public new bool DoSomething()
{
return true;
}
}
public cass Test {
public static void Main () {
Foo test = new Bar ();
Console.WriteLine (test.DoSomething ());
}
}
What confuses me here is that, if it were me I would create an instance of Bar by type Bar…
Bar test = new Bar();
I don’t understand why it would be created the way it is in the code.
This code was probably written to demonstrate the difference between overriding and hiding a base class method:
In this case instantiating a
Barobject using aFoovariable will use the base class methodDoSomething()and print outfalse. Had theDoSomethingmethod been declared as virtual in the base class and been overridden in the derived class the output would betrueas in the following example: