I always thought base.Something was equivalent to ((Parent)this).Something, but apparently that’s not the case. I thought that overriding methods eliminated the possibility of the original virtual method being called.
Why is the third output different?
void Main() {
Child child = new Child();
child.Method(); //output "Child here!"
((Parent)child).Method(); //output "Child here!"
child.BaseMethod(); //output "Parent here!"
}
class Parent {
public virtual void Method() {
Console.WriteLine("Parent here!");
}
}
class Child : Parent {
public override void Method() {
Console.WriteLine ("Child here!");
}
public void BaseMethod() {
base.Method();
}
}
Because in
BaseMethodyou explicitly call the method in the base class, by using thebasekeyword. There is a difference between callingMethod()andbase.Method()within the class.In the documentation for the
basekeyword, it says (amongst other things) that it can be used to Call a method on the base class that has been overridden by another method.