Why does C# compiler overload resolution algorithm treat static and instance members with equal signature as equal?
-
14-11-2019 - |
Question
Let we have two members equal by signature, but one is static and another - is not:
class Foo
{
public void Test() { Console.WriteLine("instance"); }
public static void Test() { Console.WriteLine("static"); }
}
but such code generate brings a compiler error:
Type 'Foo' already defines a member called 'Test' with the same parameter types
But why?
Let we compiled that successfully, then:
Foo.Test()
should output "static"new Foo().Test();
should output "instance"
Can't call the static member instead of instance one because in this case another, more reasonable compiler error will occur:
Member 'Foo.Test()' cannot be accessed with an instance reference; qualify it with a type name instead
Solution
What about, from an instance method:
Test();
What would that call? You'd probably want to give the instance method "priority" over the static method, but both would be applicable.
I would say that even if it were allowed, it would be a fundamentally bad idea to do this from a readability point of view... for example, if you changed a method which called Test
from being static to instance, it would change the meaning in a subtle way.
In other words, I have no problem with this being prohibited :)