Scenario:-
Function declared as virtual in base class and overridden in child class. See the sample code below:
public class MyClass
{
public virtual void foo()
{
Console.WriteLine("Base version of foo");
}
}
public class MyChild : MyClass
{
public override void foo()
{
Console.WriteLine("Child version of foo");
}
}
We will create objects of base and child normally and through casting in all following samples:-
MyClass obj = new MyClass();
MyChild obj2 = new MyChild();
MyClass objCastedFromChild = (MyClass)obj2;
obj.foo();
obj2.foo();
objCastedFromChild.foo();
Output:-
Base version of foo
Child version of foo
Child version of foo
so you can see the difference. In Method Hiding base class object was calling its own implementation but in this case base is calling the child class’s implementation. So in case of overriding and casting behavior changes.
Let’s continue our discussion here