"new" vs "override" for a method

E

Ethan Strauss

Hi,
This seems really basic, but I can't figure it out.
What is the difference between an inherited class overriding a base
class method and an inherited class creating a "new" method.

For example, I have a class and inherited class as follows

class Units
{
//...
public virtual bool Equiv(object obj)
{
//...
}
}

class NumberWithUnits : Units
{
//...
public override bool Equiv(object obj)
{
//...
}
new public bool Equiv(object obj)
{
}

}

Why might I want to new vs override in the method?
When I first started on this, I was actually overriding Equals and I got
weird results when I defined a method as

public bool override Equals(object obj, double tolerance)

This method did not seem to get called under any conditions until I removed
the override and added "new". Not quite sure what that means.
Thanks,
Ethan
 
J

Jon Skeet [C# MVP]

Ethan Strauss said:
This seems really basic, but I can't figure it out.
What is the difference between an inherited class overriding a base
class method and an inherited class creating a "new" method.

See http://www.yoda.arachsys.com/csharp/faq/#override.new

Basically "new" should almost *never* be used - it lets you get out of
tricky situations in a few cases, but if you don't really, really need
to use it, don't!
 
H

henk holterman

Ethan said:
This seems really basic, but I can't figure it out.
What is the difference between an inherited class overriding a base
class method and an inherited class creating a "new" method.


Quite a difference. If you define a method in both the Base and Derived
class (without override), you create a name-conflict that is signaled as
a warning (method X hides base-class member...). It is not an Error.

You can use 'new' in the Derived class method to suppress this warning.
It has no other effects.

If the base class method is virtual en the derived method is _not_
override the 'virtual method' chain is broken. The warning and use of
'new' are the same.

Only with an unbroken virtual chain you can invoke a derive method via a
base-class reference.

public bool override Equals(object obj, double tolerance)

This method did not seem to get called under any conditions until I removed
the override and added "new". Not quite sure what that means.

It won't even compile in the context of the code supplied. Overloaded
methods are treated as being completely different with respect to
virtual/override.


-HH-
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top