How to choose between new and override in C #?

It is recommended that you use redefinition instead of a new keyword in C #. Why is this a rule?

+5
source share
3 answers

"new" means that you have two completely different methods regarding the CLR - they have the same name, but they are not related to inheritance. This means that if you run:

Base b = new Derived();
Derived d = new Derived();
b.MyMethod(); // Calls Base.MyMethod
d.MyMethod(); // Calls Derived.MyMethod

This can lead to very difficult to understand code.

Usually, if you want to use different methods, call them different things. A common reason to use the same name (and signature) is to override the behavior of the base class method. At this point, you have no choice but to keep the name / signature the same.

+12
source

, "", .

+3

. , . , "", , , - , ...

"", NEW "" . , , of ( ) . ...

Although, when the code gets into your hardware, it is nothing but a completely different method with the same name and the same signature. If an overridden method replaces every single call, including a base class assembly, with your new method ...

Thus, comparing them is like comparing cars and errors ... birds or something like that.

0
source

All Articles