Should the following code give a warning?
class Foo { public void Do() { /*...*/ } /*...*/ } class Bar : Foo { public static void Do() { /*...*/ } /*...*/ }
It gives:
‘Warning CS0108: ‘Bar.Do()’ hides inherited member ‘Foo.Do()’. Use the new keyword if hiding was intended.’
If I make a change to the code:
class Foo { public static void Do() { /*...*/ } /*...*/ } class Bar : Foo { public void Do() { /*...*/ } /*...*/ }
I get the same warning.
If I make the following change, however, the warning goes away.
class Foo { public void Do() { /*...*/ } /*...*/ } class Bar : Foo { new public static void Do() { /*...*/ } /*...*/ }
Let me make a further change:
class Foo { public void Do() { /*...*/ } /*...*/ } class Bar : Foo { new public static void Do() { new Bar().Do();/*...*/ } /*...*/ }
This does not compile:
‘Error CS0176: Member ‘Bar.Do()’ cannot be accessed with an instance reference; qualify it with a type name instead.’
So, I lose access to my inherited method via an instance reference from a static method!
What would be the logic behind it? Or did I make a typo somewhere?
I came across this when I was trying to define a static method ‘Show’ for my form derived from ‘Form’.
Where do you think the bug is? The fact that there is a warning is absolutely right. From the C# 3.0 spec, section 10.3.4:
The fact that your method invocation fails is subtler, but it’s basically because the member lookup algorithm picks the static method, and then this part of section 7.5.5.1 is used: