Monday, November 15, 2010

What's new

C# new method modifierPurpose: If you want to redefine a method visible to a derived class, earlier defined in some base class in the hierarchy, do it with new.
False : new is only for redefining virtual methods.
new is also for redefining methods marked as virtual.


True : new hides the base implementation.
But it is possible to still access the implementation in base.
False : new cannot be used with static membersA static member in C# can't be marked as override, virtual or abstract. However it is possible to hide a base class static method in a derived class by using the keyword new.


The following example should help out:
class A { public string MyName() {return "A";}}
class B:A { new public virtual string MyName() {return "B";}}
class C: B {public override string MyName() {return "C";}}
class D:C {new public string MyName() {return "D";}}


A a = new B(); a.MyName() returns "A"
B b = new C(); b.MyName() returns "C";
D d = new D(); d.MyName() returns "D";

Note that polymorphic behavior is displayed by b. Virtual dispatch is used since 'virtual' is used.
But the polymorphic behavior is limited between B & C and does not extend to D, since in D, we have redefined the method.

No comments: