Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of "static new" modifier for a function?

Today, I found something in legacy code. It has "static new" for one function. It looks like this.

class Foo {     public static void Do()     {         Console.WriteLine("Foo.Do");     } }  class Bar: Foo {     public static new void Do()     {         Console.WriteLine("Bar.Do");     } } 

I don't understand the static new modifier for the Do method in class Bar. In C#, static method can only be invoked with class name instead of object name. So, I don't think there is any difference between having the "new" and not.

Generally, if some syntax is unnecessary, C# just treat it is error. Anybody has any idea about why C# allows such syntax?

like image 731
Morgan Cheng Avatar asked Mar 19 '09 06:03

Morgan Cheng


2 Answers

If you remove the new from your code you get:

warning CS0108: 'Bar.Do()' hides inherited member 'Foo.Do()'. Use the new keyword if hiding was intended.

The C# compiler just warns you that you might be doing something you did not intend and asks you to insert the new keyword to confirm that you know what you are doing. Besides suppressing the warning, it has no other effects.

like image 149
Rasmus Faber Avatar answered Sep 21 '22 11:09

Rasmus Faber


That applies only for external callers. Remember that you can call a static method of the base class, so something like this is valid:

class Foo {     public static void Do() { Console.WriteLine("Foo.Do"); } } class Bar : Foo // :Foo added {     public static void Something()     {         Do();     } } 

This is why the warning tells you to put the new, you want to avoid any confusion when doing this:

class Foo {     public static void Do() { Console.WriteLine("Foo.Do"); } } class Bar : Foo // :Foo added {     public static void Something()     {         Do();     }     public static new void Do() { Console.WriteLine("Bar.Do"); } } 
like image 35
eglasius Avatar answered Sep 23 '22 11:09

eglasius