9

I accidentally come across this page new keyword in method signature and I found that some examples that was given in this post are not accurate (e.g. Second one)

I think the "new" is already there if you don't say "override". The only difference is that you will get a greenline (warrning?) if you don't write either "override" (for virtual method) or "new". You can still choose not to write "new" and it will still work. Am I right in saying this, or am I missing something important?

Community
  • 1
  • 1
Michael Sync
  • 4,834
  • 10
  • 40
  • 58
  • 2
    This is dupe - http://stackoverflow.com/questions/3117838/why-do-we-need-the-new-keyword-and-why-is-the-default-behavior-to-hide-and-not-o – P.K Dec 14 '11 at 10:15
  • 4
    Look at this answer from Eric Lippert http://stackoverflow.com/a/3118480/149190 – P.K Dec 14 '11 at 10:16
  • with the second I think you mean this one: http://stackoverflow.com/a/1014309/112407 (not all have the same sort order) that is indeed accurate and highlights why it's a warning. The code might very well do something else that want is expected. compile time types are seldom more important than runtime type but in this case it is – Rune FS Dec 14 '11 at 10:20
  • Thanks for sharing Eric Lippert's answer.. but I couldn't make it as answer since it's in comment. thanks a lot. – Michael Sync Dec 15 '11 at 03:19

2 Answers2

10

Yes it doesn't do anything except hiding that warning.

The warning is only there to make sure you know what you're doing, since hiding is rarely a good idea. But making override the default would cause versioning problems if the base class introduces a new virtual method and the derived class happens to have a matching but independent method which now accidentally overrides the inherited method.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
1

I believe it was basically so you could state intent in your code.

So if you want to hide a method in a base class you use the new directive to tell yourself and others, that you did it deliberately. i.e. you didn't add a totally new method with the same name as an existing onne in ignorance.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39