C# has two keywords for decorating methods, new
and override
, that have almost identical effects.
. They are both used to override a method on a base class, but how do they differ? A lot of documentation I’ve read is pretty vague, saying something like, “Overriding a virtual method with the new
keyword hides, rather than overrides, the base class implementation of the method.” Here is what that means:
The override
keyword creates a true run-time method override, whereas the new
keyword affects only compile-time method identification. This is a bit like the difference between overriding and overloading. So if your object is declared as Animal
but you’ve really got a Dog
, calling a method with override
will execute the Dog
implementation, but calling a method with new
will execute the Animal
implementation, because that’s all the compiler can see.
If you have a C++ background, you can think of this in terms of a virtual method table or dispatch table. In C#, only methods marked virtual
get such a table. The override
keyword adds a new entry to that table, whereas new
does not.
C# is more conservative than Java when it comes to method overrides. In Java, by default you can override any method, after accounting for the usual access modifiers (public
/protected
/private
). This led to problems where subclasses could break functionality by overriding methods the base class didn’t expect. In C#, you can only override those methods the base class explicitly permits. So you can only use override
if the base class method is marked virtual
. However, you can use new
on any method. As long as the compile-time type of an object is the subclass, your new
method will be called, but the base method will continue to be called elsewhere, including (most importantly) from within the base class.