Static and Instance Methods with the same names #7853
-
I am running into a weird issue and I'm hoping someone can explain why this happens and (if possible) enhance C# to make this possible. First, this code compiles fine:
But once I introduce a base class, I get errors:
Why does this happen and shouldn't this be possible? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I cannot give you a definitive quote from the specification, but I quickly skimmed through the relevant parts of overload resolution. This might be related to the fact that the specification mentions that "Each of these contexts defines the set of candidate function members and the list of arguments in its own unique way. For instance, the set of candidates for a method invocation does not include methods marked override (§12.5), and methods in a base class are not candidates if any method in a derived class is applicable (§12.8.9.2)." In your example, in the first case both the static and instance method are in the candidate set. In the second case only the static method in the derived type is deemed applicable by looking at the parameter/argument list (overrides are not included). Because it's the only method in the set it's automatically selected and the compiler errors at a later stage. I wonder if my analysis is correct here 🤔 |
Beta Was this translation helpful? Give feedback.
Addendum: I generally agree with you and also think it would make sense/be more intuitive to exclude static non-extension methods from the set of candidates initially, if we're in an instance context.