Saturday, September 13, 2008

C#: new vs. override (part 2)


Derived:Base
Base:BaseBase
BaseBase:BaseBasebase

Derived d = new Derived();
BaseBasebase bbb = d;
BaseBase bb = d;
Base b = d;

All these classes have functions as follows :

bbb - virtual public void FooChain()
bb - override public void FooChain()
b - virtual new public void FooChain()
d - override public void FooChain()

Then the result is as follows:

bbb.FooChain();//BaseBase FooChain
bb.FooChain(); //BaseBase FooChain
b.FooChain(); //Derived FooChain
d.FooChain(); //Derived FooChain

In a hierarchy when we use new(as in Base class), it breaks the chain, so now, when bbb.FooChain() is called, the type is BBB, and as per our rule "overide execuetes derived" and FooChain() in the actual object of D is overridden, we get the most derived FooChain() which is not a "new" Function, so we get "BaseBase FooChain".

No comments: