What is the difference between new and override

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

We can use new or override to rewrite a method in an child class.
But what is the difference between new and override?
 
Say you do this:
------------
DerivedType derivedInstance = new DerivedType();
BaseType baseVar = derivedInstance;
baseVar.CallMethod();
-------------

If the DerivedType.CallMethod() is defined as "new", the above code will
code the BaseType version. If it is defined as "override", it wil call the
DerivedType version.

If you are using inheritance to get polymorphism, you probably want
override.

Hope this helps,
Rachel
 
But what is the difference between new and override?

The other responses covered the technical details so here is just a bit of
intuition that might help.

You will almost always want "override" - it is rare to use "new".

override = more specific version of the same operation
new = new and unrelated method with same name and params as base method

If we put a method in a derived class that hides a base method, then we are
most likely being silly or careless. The compiler notices what is going on
and gives us a warning. The most common thing to do at this point is change
the name or param list of the derived method so there is no longer a
conflict. If we want to keep both methods the same, we need to acknowledge
that we really do want to hide the base method by adding "new".
 
You can also use new for non-virtual methods, events and properties(you
can't with override).

For example, we have a custom control library that is used as the basis for
our company's suite of applications. To deter the developers in other groups
from trying to change say, the background color of a control, we use "new"
to hide the underlying Control.BackgroundColor property So that if they set
the background color of one of our controls, we simply ignore it.

This isn't foolproof, though. If the end-developer wanted to get around it,
he/she could simply cast to the base class of the control and call the
BackgroundColor property that way. Of course, then we'd have to take him out
back and beat the $@#% out of him which is a much more effective deterrent.

Pete
 
Back
Top