14

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

plinth
  • 48,267
  • 11
  • 78
  • 120
abatishchev
  • 98,240
  • 88
  • 296
  • 433

1 Answers1

13

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 :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 3
    In that case the compiler should enforce you using either this.Test() or Foo.Test(). Your argumentation also applies to instance variables vs. parameters, which may also have naming comflicts. – codymanix May 17 '11 at 15:55
  • @codymanix: I think I'm still happier for this to just be prohibited. I find it relatively rare for the same method to make sense (with the same parameters) as both an instance and static method... – Jon Skeet May 17 '11 at 15:57
  • @codymanix: +1 but i think i understood why is it prohibited: let we have a such class and it compiles fine; and another two - one with instance method, and another with static. From declaration point of view all 3 are equal. But from usage - not: first will require additional code to resolve the ambiguity while 2 others - not. That's not good. – abatishchev May 17 '11 at 16:42
  • Jon, thank you for use case that exposes the possible issue. I also had no problem until I have to mock a factory with static-only methods: I can't add an instance-method returning the same. So have to invent a bicycle :) – abatishchev May 17 '11 at 16:45