Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between new and override

Wondering what the difference is between the following:

Case 1: Base Class

public void DoIt(); 

Case 1: Inherited class

public new void DoIt(); 

Case 2: Base Class

public virtual void DoIt(); 

Case 2: Inherited class

public override void DoIt(); 

Both case 1 and 2 appear to have the same effect based on the tests I have run. Is there a difference, or a preferred way?

like image 784
Shiraz Bhaiji Avatar asked Sep 09 '09 11:09

Shiraz Bhaiji


People also ask

What is the difference between new and override keywords in method declaration?

The simple difference is that override means the method is virtual (it goes in conduction with virtual keyword in base class) and new simply means it's not virtual, it's a regular override.

Why override is used in C#?

override (C# reference) The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event. An override method provides a new implementation of the method inherited from a base class.

What is override as used in inheritance?

A derived class has the ability to redefine, or override, an inherited method, replacing the inherited method by one that is specifically designed for the derived class.

Can you override without virtual?

No, you cannot override a non-virtual method. The closest thing you can do is hide the method by creating a new method with the same name but this is not advisable as it breaks good design principles.


1 Answers

The override modifier may be used on virtual methods and must be used on abstract methods. This indicates for the compiler to use the last defined implementation of a method. Even if the method is called on a reference to the base class it will use the implementation overriding it.

public class Base {     public virtual void DoIt()     {     } }  public class Derived : Base {     public override void DoIt()     {     } }  Base b = new Derived(); b.DoIt();                      // Calls Derived.DoIt 

will call Derived.DoIt if that overrides Base.DoIt.

The new modifier instructs the compiler to use your child class implementation instead of the parent class implementation. Any code that is not referencing your class but the parent class will use the parent class implementation.

public class Base {     public virtual void DoIt()     {     } }  public class Derived : Base {     public new void DoIt()     {     } }  Base b = new Derived(); Derived d = new Derived();  b.DoIt();                      // Calls Base.DoIt d.DoIt();                      // Calls Derived.DoIt 

Will first call Base.DoIt, then Derived.DoIt. They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.

Source: Microsoft blog

like image 89
rahul Avatar answered Oct 13 '22 07:10

rahul