this is a small code which shows virtual methods.
class A
{
public virtual void F() { Console.WriteLine("A.F"); }
}
class B: A
{
public override void F() { Console.WriteLine("B.F"); }
}
class C: B
{
new public virtual void F() { Console.WriteLine("C.F"); }
}
class D: C
{
public override void F() { Console.WriteLine("D.F"); }
}
class Test
{
static void Main()
{
D d = new D();
A a = d;
B b = d;
a.F();
b.F();
}
}
This code is printing the below output:
B.F
B.F
I can not understand why a.F() will print B.F ?
I thought it will print D.F because Class B overrides the F() of Class A, then this method is being hidden in Class C using the “new” keyword, then it’s again being overridden in Class D. So finally D.F stays.
but it’s not doing that. Could you please explain why it is printing B.F?
It will find
F()as follows.class Aclass Bclass Cclass DNow
F()will be found inA, andB. ThusB.F()will be invoked. Inclass CF() is different (as it is new implementation and does not override from A/B). So In 3rd step, c.F() will not be found. In Class D, it overrides new function created by C, thus it will also not be found.Due to new keyword, the resulting code is like following (with respect to virtual override)