tags:

views:

324

answers:

3

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

+11  A: 

"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.

Jon Skeet
+1  A: 

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

Quibblesome
There *IS* no usecase, it's *another* method which happens to have the "same name", period...
Thomas Hansen
The use case is pretty simple, actually. The steps are: 1) You derive from a class which isn't under your control (e.g. one from the framework). 2) You introduce a new method called Foo(). 3) A later version of the base class also introduces Foo(). 4) You get a compiler warning, and fix it.
Jon Skeet
The options for fixing it are: a) Rename the method (not always feasible). b) Add the "new" modifier. And yes, this is a nasty situation which you should avoid wherever possible - but it's nice that C# at least lets you cope with it.
Jon Skeet
Ah, I see. So it's to help with compatability issues when upgrading and the framework potentially stealing a name already in use. That makes sense. Thanks Jon! :D
Quibblesome
A: 

This is actually not a choice you have. This is imposed upon you by however created the base class. If there exists a method with the same name and it is marked as "virtual" then you should use override unless you want to have some seriously funny bugs appearing down the road when people starts casting objects of your class to the base class...

Though if that method is NOT marked as "virtual" then the only way to create a NEW method is by using the "new" keyword. Note though that this will not replace method invocations where the reference is of typeof(baseclass) to your method. So this is mostly just syntactical sugar to create a new method with the same name and the same signature...

Though when code hits your iron it's nothing else then a completely different method with the same name and the same signature. Where an overridden method will replace every single call including those in the base class assembly to your new method...

So comparing them is like comparing cars and errh... birds or something...

Thomas Hansen