Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chose between new and override in C#?

Tags:

c#

It is advised to use override instead of new key word in C#. Why that rule?

like image 542
suhair Avatar asked Dec 04 '08 13:12

suhair


2 Answers

"new" means you've got two completely different methods as far as the CLR is concerned - they happen to have the same name, but they're unrelated in terms of inheritance. That 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 make for some very hard-to-understand code.

Usually if you want different methods, call them different things. The normal reason to use the same name (and signature) is to override the behaviour of a base class's method. At that point you don't have any choice but to keep the name/signature the same.

like image 68
Jon Skeet Avatar answered Nov 02 '22 23:11

Jon Skeet


I'm still trying to work out what the use case is for "new" aside from horrid hackery.

like image 34
Quibblesome Avatar answered Nov 03 '22 00:11

Quibblesome