Michael Sync
Michael Sync

Reputation: 5004

"new" keyword in C# is just for making the warning disappeared, isn't it?

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?

Upvotes: 9

Views: 385

Answers (2)

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

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.

Upvotes: 1

CodesInChaos
CodesInChaos

Reputation: 108820

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.

Upvotes: 10

Related Questions