Difference between new and override
Solution 1
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
Solution 2
virtual: indicates that a method may be overriden by an inheritor
override: overrides the functionality of a virtual method in a base class, providing different functionality.
new: hides the original method (which doesn't have to be virtual), providing different functionality. This should only be used where it is absolutely necessary.
When you hide a method, you can still access the original method by up casting to the base class. This is useful in some scenarios, but dangerous.
Solution 3
In the first case you are hiding the definition in the parent class. This means that it will only be invoked when you are dealing with the object as the child class. If you cast the class to its parent type, the parent's method will be invoked. In the second instance, the method is overridden and will be invoked regardless of whether the object is cast as the child or parent class.
Solution 4
new
means respect your REFERENCE type(left-hand side of=
) , thereby running reference types's method. If redefined method doesn't havenew
keyword, it is behaved as it has. Moreover, it also known as non-polymorphic inheritance. That is, “I’m making a brand new method in the derived class that has absolutely nothing to do with any methods by the same name in the base class.” - by said Whitakeroverride
, which must be used withvirtual
keyword in its base class, means respect your OBJECT type(right-hand side of=
), thereby running method overriden in regardless of reference type. Moreover, it also known as polymorphic inheritance.
My way to bear in mind both keywords that they are opposite of each other.
override
: virtual
keyword must be defined to override the method. The method using override
keyword that regardless of reference type(reference of base class or derived class) if it is instantiated with base class, the method of base class runs. Otherwise, the method of derived class runs.
new
: if the keyword is used by a method, unlike override
keyword, the reference type is important. If it is instantiated with derived class and the reference type is base class, the method of base class runs. If it is instantiated with derived class and the reference type is derived class, the method of derived class runs. Namely, it is contrast of override
keyword. En passant, if you forget or omit to add new keyword to the method, the compiler behaves by default as new
keyword is used.
class A
{
public string Foo()
{
return "A";
}
public virtual string Test()
{
return "base test";
}
}
class B: A
{
public new string Foo()
{
return "B";
}
}
class C: B
{
public string Foo()
{
return "C";
}
public override string Test() {
return "derived test";
}
}
Call in main:
A AClass = new B();
Console.WriteLine(AClass.Foo());
B BClass = new B();
Console.WriteLine(BClass.Foo());
B BClassWithC = new C();
Console.WriteLine(BClassWithC.Foo());
Console.WriteLine(AClass.Test());
Console.WriteLine(BClassWithC.Test());
Output:
A
B
B
base test
derived test
New code example,
Play with code by commenting in one-by-one.
class X
{
protected internal /*virtual*/ void Method()
{
WriteLine("X");
}
}
class Y : X
{
protected internal /*override*/ void Method()
{
base.Method();
WriteLine("Y");
}
}
class Z : Y
{
protected internal /*override*/ void Method()
{
base.Method();
WriteLine("Z");
}
}
class Programxyz
{
private static void Main(string[] args)
{
X v = new Z();
//Y v = new Z();
//Z v = new Z();
v.Method();
}
Solution 5
try following: (case1)
((BaseClass)(new InheritedClass())).DoIt()
Edit: virtual+override are resolved at runtime (so override really overrides virtual methods), while new just create new method with the same name, and hides the old, it is resolved at compile time -> your compiler will call the method it 'sees'
Related videos on Youtube
Shiraz Bhaiji
Architect / dev lead / .net programmer Manager at Evry http://www.evry.no/ Board Member Oslo Software Architecture http://www.meetup.com/Oslo-Software-Architecture/
Updated on February 24, 2020Comments
-
Shiraz Bhaiji over 4 years
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?
-
Jon Skeet almost 15 yearsDuplicate of many questions, including stackoverflow.com/questions/159978/…
-
-
Raquel over 11 yearsCould you post the warning or error you are receiving. This code worked fine when I originally posted it.
-
Raquel over 11 yearsThis should all be pasted within your entry point class (Program). That was removed to allow for better formatting on this site.
-
AminM over 10 years
This indicates for the compiler to use the last defined implementation of a method
. how can find last defined implementation of a method?? -
csoltenborn over 9 yearsStart from a concrete class, check whether it has an implementation of the method of interest. If it does, you're done. If it doesn't, go one step up in the inheritance hierarchy, i.e., check whether the super class has the method of interest. Continue until you have found the method of interest.
-
John Evans Solachuk over 7 yearsWhy is up casting a method that hides the base method dangerous? Or are you implying that up casting in general is dangerous?
-
Jon B over 7 years@Mark - a caller might not be aware of the implementation, causing accidental misuse.
-
Erik Bongers about 6 yearsAlso note that you can only
override
a method when the base class defines the method asvirtual
. The wordvirtual
is the base class saying "Hey, when I call this method, it could have virtually been replaced by a derived implementation, so I don't really know in advance what method implementation I'm actually calling at runtime. Sovirtual
signifies is a placeholder for a method. This implies that methods that are not marked asvirtual
can not be overridden. But you can replace any non-virtual method in a derived class with the modifiernew
, only accessible at derived level. -
BYS2 about 5 yearsinstanceC.DoIt(); would give you C::DoIt(), not B::DoIt()
-
Aaron Franke about 5 yearsCan you use
override
and/ornew
withoutvirtual
on the parent method? -
Stefan Steiger over 3 years@Mark: Because if you cast it to the base type, it uses the hidden method, instead of the "new" one. This happens for sure if you implement interfaces explicitly.
-
Ferazhu about 3 years"Override is with respect to the right-hand of assignment, new is with respect to the left-hand of assignment". Good way of remembering this, thanks!
-
Joe Phillips almost 3 yearswhat if you literally call
base.DoIt()
inside the Derived class?