• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C# name collision between static and instance methods

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
I must not have run into this in a long time, as it surprised me.

Code:
public class MyClass
{
[INDENT]public void A(int i) { }[/INDENT]
[INDENT]public static void A(int i){}[/INDENT]
}

The compiler wouldn't let me do this...

Type 'MyClass' already defines a member called 'A' with the same parameter types

It surprised me because I would have assumed this was legal. When I thought about why I would have assumed that, it was because I was thinking that the method does have a different implicit signature, i.e. the instance method takes a this pointer, and the static method does not. Why can't the compiler tell the difference between these?

Edit: damn, anyone know how to control the height of the code window?
 
Last edited:
Perhaps it's because I haven't tried this in C#, but are you allowed to have a static method inside of a non-static class?
 
Think of it this way. Your code looks like this

Code:
 MyClass bob;
bob.A(3);

Which A would be called? Both would fit the call.
 
Think of it this way. Your code looks like this

Code:
 MyClass bob;
bob.A(3);

Which A would be called? Both would fit the call.

bob.A is accessing the instance method.

Code:
internal class Program
  {
    private static void Main(string[] args)
    {
      var f = new Foo();
      f.Bar();
    }
  }

  public class Foo
  {
    public static void Bar()
    {
      Console.WriteLine("Static Bar");
    }
  }

That's not valid C#.
 
How do you use "A(int)" from INSIDE the class?

That's where the problem is.

Correct, the reason you cannot is because static methods can also be called from non-static context without needing to prepend the class name, eg MyClass.A(3); so:

// Instance
MyClass c = new MyClass();
c.A(3);

// Instance from within the class
this.A(3);

// Static
MyClass.A(3);

// Within the class (problem)
A(3);

The issue with the last one is that the compiler does not know whether to use the static or instance method. You could infer that it should be the instance as the class was invoked in an instance context, however because there is no enforcement of class or instance prepending in front of methods calls within the class the compiler cannot support this sort of program structure.
 
Last edited:
Back
Top