When I override a virtual function, I've always assumed the override method would be called only if an object is of that child class type (and not the base type). The following statements in this answer suggest the override will always be called, even if the object is of base type:
Difference between new and override
Even if the method is called on a reference to the base class it will use the implementation overriding it.
The method is overridden and will be invoked regardless of whether the object is cast as the child or parent class.
So I made this setup:
public class Test
{
public virtual void DoSomething()
{
Console.WriteLine("Base called");
}
}
public class TestChild : Test
{
public override void DoSomething()
{
Console.WriteLine("Child called");
}
}
class Program
{
static void Main(string[] args)
{
var test = new Test();
test.DoSomething();
}
}
Which results in the parent (Test) method being called, not the override. So when those statements say the override will be called, even if the object is cast as child or parent, what exactly do they mean?
Do these statements not include if the object is instantiated as the parent type? (rather than cast)