C # cannot declare static and non-static methods with the same parameters?

If I try to declare static and non-static methods with the same parameters, the compiler returns an error: type 'Test' already defines a member named "Load" with the same parameters.

class Test { int i = 0; public int I { get { return i; } set { i = value; } } public bool Load(int newValue) { i = newValue; return true; } public static Test Load(int newValue) { Test t = new Test(); tI = newValue; return t; } 

As far as I know, these two methods cannot be mixed, the non-static method is called on the object, while the static method is called on the class, so why doesn't the compiler allow something like this, and is there a way to do something like that?

+6
source share
7 answers

If your Test class had a method like this:

 public void CallLoad() { Load(5); } 

the compiler does not know what kind of load to use (). Calling a static method without a class name is fully permitted for members of the class.

As for how to do something like this, I suggest that it is best to use methods that are similar, but with different names, such as renaming the static method to LoadTest() or LoadItem() .

+10
source

Inside the class itself, you call both instance methods and static methods without an instance or class name, thereby making two indistinguishable if the names and parameters are the same:

 class Test { public void Foo() { Load(0); // Are you trying to call the static or the instance method? } // ... } 
+4
source

A method signature is a combination of a name and parameters (number and types).

In your case, your 2 methods have the same identical signature. The fact that one is static and the other has nothing to do with accepting them as valid methods for a class.

+1
source

I do not think so. if the non-static method in this class calls Load (intValue). which method will be called?

0
source

Both methods have the same name defined in the same class (scope) and with the same signature. C # does not allow this.

0
source

The problem is not related to this or classname entry. C # specifications allow you to call static methods using object instances:

 AClass objectA = new AClass(); objectA.CallStaticMethod(); 

This code is valid, so the compiler never knows if you are calling a static or instance method.

0
source

In C #, a method cannot be overloaded with a return type. It should at least have a different set of parameters, regardless of whether the method is static or not.

0
source

All Articles