New vs Override

Override is bottom up approach, if the method is re-implemented in the subclass than the compiler will always use the subclass method. Even if you call the base class method the compiler will first pick the method from derived class.

New will basically select the method from subclass if there is the keyword new in the method. If you invoke the base class than base class method will be called as in the example below.

static void Main()
{
	Overrider over = new Overrider();
	BaseClass b1 = over;
	over.Foo();                         // Overrider.Foo
	b1.Foo();                           // Overrider.Foo
	
	Hider h = new Hider();
	BaseClass b2 = h;
	h.Foo();                           // Hider.Foo
	b2.Foo();                          // BaseClass.Foo
}

public class BaseClass
{
	public virtual void Foo()  { Console.WriteLine ("BaseClass.Foo"); }
}

public class Overrider : BaseClass
{
 	public override void Foo() { Console.WriteLine ("Overrider.Foo"); }
}

public class Hider : BaseClass
{
	public new void Foo()      { Console.WriteLine ("Hider.Foo"); }
}

Leave a Reply

Your email address will not be published. Required fields are marked *