"new" methods are a rather dangerous feature IMO. So, you have to be careful
when you use it. Given its semantics, it is difficult for the compiler to
give you this kind of warning.
I try to restrict the use of new to cases where the new method performs
exactly the same thing as the method in the superclass but has a different
return type. The typical pattern is the following:
class BaseContainer { }
class BaseElement
{
private BaseContainer _container;
public BaseContainer Container { get { return _container; } }
}
class DerivedContainer : BaseContainer {}
class DerivedElement : BaseElement
{
public new DerivedContainer Container { get { return
(DerivedContainer)base.Container; } }
}
The idea is to get a correctly typed API in the derived API. (this is called
type covariance and languages like Eiffel support it).
But I don't allow any other use of new methods, because anything else
(redefining a method to give it different semantics than what it has in the
base class) is just heading for trouble. If the two methods do different
things, you get different results depending on whether you call them from a
BaseXxx or a DerivedXxx (the types that the compiler sees, not the runtime
types), and this can lead to very tricky bugs.
Bruno.
"Daniel Jin" <an*******@discussions.microsoft.com> a écrit dans le message
de news:7D**********************************@microsof t.com...
----- Jon Skeet [C# MVP] wrote: -----
> Absolutely. The point of "new" is that it's defining a completely
> different method. Whether or not it's a good idea to use this fact
> arbitrarily is a different matter.
Just seemed a little odd to me since Print from base class isn't
hidden because the difference in visibility. Wouldn't it be better if the
compiler at least generated a warning? say hypothetically, I wanted to make
the new Print() public in Derived, but for some reason I forgot to mark it
with public, so it defaulted to private. compiler doesn't complain. now I
call Derived.Print(), but the base method executes. It'd be probably very
easy to spot a mistake like this, but still, warning would be nice.