Scenario:-
Function present in both base class and child class. This concept is called Method hiding. See the sample code below:
public class MyClass
{
public void foo()
{
Console.WriteLine("Base version of foo");
}
}
public class MyChild : MyClass
{
public new void foo()
{
Console.WriteLine("Child version of foo");
}
}
Without new keyword compiler will give a warning that you are hiding the base class implementation. We will create objects of base and child normally and through casting in 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
Base version of foo
so in normal scenarios follow the simple rule. Thy object thy function.
Let's continue our discussion in next article here