Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# cannot declare static and non static methods with same parameters?

Tags:

methods

c#

class

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

    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();
            t.I = newValue;
            return t;
        }

As far as I know these two methods can not be mixed, non static method is called on object whereas static method is called on class, so why does compiler not allow something like this and is there a way to do something similar?

like image 861
Dragan Matic Avatar asked Jan 14 '13 10:01

Dragan Matic


1 Answers

If your Test class had a method like this:

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

the compiler would not know which Load() to use. Calling a static method without the class name is entirely allowed for class members.

As for how to do something similar, I guess your best bet is to give the methods similar but different names, such as renaming the static method to LoadTest() or LoadItem().

like image 55
JLRishe Avatar answered Sep 19 '22 10:09

JLRishe