(Just to supplement other answers, and comments by myself.)
When one uses new
, the class (or struct, or interface) will have two same-looking members, one inherited from a base type, and one declared by the type itself. Avoid that!
Important: Just because you say new
, you will not "remove" the old member. It is still there, and can easily be called. The new
member does not replace the inherited one. It is an unrelated member which happens to have the same name.
It is not good to have two or more members in a type that look the same. It leads to confusion. Consider the code:
interface IOne
{
void Y();
}
interface ITwo
{
void Y();
}
interface IBoth : IOne, ITwo
{
}
class Test
{
static void M(IBoth obj)
{
obj.Y(); // must not compile!
}
}
The type IBoth
has two members (both inherited) which look the same. Depending on what concrete class obj
is, those methods might have different implementations. The call obj.Y()
is ambiguous. You will have to cast obj
to one of the base interfaces to resolve this.
Then consider this code:
interface IBase
{
void Y();
}
interface IDerived : IBase
{
/* new */ void Y();
}
class Test
{
static void M(IDerived obj)
{
obj.Y(); // allowed; IDerived has two Y, but one hides the other
}
}
This time, there are two Y()
, but one is sort of "nearer" than the other one. So the nearer one is preferred. However the compiler will give you a warning if you don't use new
. If you do use new
, that changes nothing other than making the compile-time warning go away. It is really a bad idea to make two Y()
on purpose.
This situation can happen if the base type (here IBase
) is written by some other vendor/supplier. Example: Maybe you introduced Y()
in your interface at a time when the base didn't have that functionality. But then the vendor of IBase
is releasing a new version of their product where IBase
has the Y()
. Now if you compile your code against their new version, "your" Y()
will still be called, not theirs. But it will give this warning. The warning goes away if you include new
. But it is better to either (1) remove your Y()
method completely if you determine that the vendor's Y()
does the job, or (2) rename your Y()
method to some unused name.
If what you wanted was polymorphism, of course use abstract
/virtual
(class members only) combined with override
(in the inheriting class). override
will not introduce any new members, just a new implementation of an existing (inherited) member. This can be done for non-static members (typically methods or properties) only.