Scenario:-
Function present in base class as virtual but not present 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
{
}
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
Base version of foo
Base version of foo
so no difference from scenario 3. 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 here