Scenario :- Function present in base class not present in child class.
public class MyClass { public void foo() { Console.WriteLine("Base version of foo"); } } public class MyChild : MyClass { }
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
Base version of foo
Base version of foo
Members are searched from child to base when there is no implementation in child it is first searched in immediate base and so on till it’s found or a compilation error comes. Since there is no function in child with name foo all the three objects will call base version of foo.
Let’s continue our discussion in next article here