new obscures the method with a completely new method (which may or may not have the same signature) instead of overriding it (in this case, the new method must have the same signature), which means that polymorphism will not work. For example, you have the following classes:
class A { public virtual int Hello() { return 1; } } class B : A { new public int Hello(object newParam) { return 2; } } class C : A { public override int Hello() { return 3; } }
If you do this:
A objectA; B objectB = new B(); C objectC = new C(); Console.WriteLine(objectB.Hello(null));
Since you can define new method signatures with new , the compiler cannot know that instance A is actually an instance of B , and the new method B must be available. new can be used when the method of the parent object, property, field or event is not declared using virtual , and due to the lack of virtual compiler will not "search" for the inherited method. However, it works with virtual and override .
I highly recommend you avoid new ; at best, this is confusing because you define a method with a name that can be recognized by something else, and in the worst case, it can hide errors, introduce seemingly impossible errors, and make it difficult to extend functionality.
Ryan Jul 04 2018-11-11T00: 00Z
source share