Scenario:-
Function declared as abstract in base class and overridden in child class. See the sample code below:
public abstract class MyClass
{
public abstract void foo();
}
public class MyChild : MyClass
{
public override void foo()
{
Console.WriteLine("Child version of foo");
}
}
Now we can’t create base class object directly as base class is now an abstract class and thus objects can now be creates via casting only. We will create
Objects of child class normally and base class object through casting in following sample:-
//MyClass obj = new MyClass(); //Not possible now
MyChild obj2 = new MyChild();
MyClass objCastedFromChild = (MyClass)obj2;
obj2.foo();
objCastedFromChild.foo();
Output:-
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