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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With