Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 421
Michael Sync Avatar asked Dec 14 '11 10:12

Michael Sync


2 Answers

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.

like image 185
CodesInChaos Avatar answered Sep 26 '22 01:09

CodesInChaos


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.

like image 27
Tony Hopkinson Avatar answered Sep 24 '22 01:09

Tony Hopkinson