C# provides following signature characteristics to be used while function overloading.
We know that for overloading takes into consideration only arguments; their number and types, but the objective of polymorphism is to provide same name but different usage depending upon calling strategy.
If I have a class containing two methods with the same name and signature, while one is static and another is not, C# compiler throws an error; "Class already defines a member called 'foo' with the same parameter types".The call to both the methods are going to be different; one with the object name and the static one with a class name. Hence there is no ambiguity with calling strategy. Then why does it throw an error?
class Example {
public void foo() { }
public static void foo() { }
}
class Program
{
static void Main(string[] args)
{
Example e = new Example();
e.foo();
}
}
Reason why it is throwing an error is that static methods can be called from non-static methods without specifying type name. In this case, compiler won't be able to determine, which method is being called.
public class Foo()
{
public static void MyMethod() {};
public void MyMethod() {}
public void SomeOtherMethod()
{
MyMethod(); // which method we're calling static or non-static ?
}
}
EDIT
Just found this SO post regarding your case. You might want to check it also.
But you can declare a local variable with the same name as an existing field. And you can excplicitly refer to that field using
this
. Here would be the same - this.MyMethod - instance; MyMethod or Foo.MyMethod - static.@ViktorArsanov it's not about what you can or can't do here, it's all about how compiler would interperet this piece of code. It is legal to write this c# code, yet there is no way for compiler to understand which method should be called.
This answer is incorrect. Imagine if the compiler dictated for the language design team what is or isn’t legal, rather than the other way around. Since a solution (like the one Viktor suggested) is possible, and as Viktor mentioned has already been accepted by the language in a different place, the only question that remains now is why did the language design team not allow static/non-static members to have the same signiture/name? See my answer for the correct information.