C # Static class property

I was shown an example today, and I just wanted to test if both of them would actually have the same effect, and it doesn't, what's the difference between them.

It:

private static Service1Client _myFoo;

static ServiceLayer()
{
    MyFoo = new Service1Client();
}

public static Service1Client MyFoo
{
    get { return _myFoo; }
    set { _myFoo = value; }
}

      

Just a long way to do it:

public static Service1Client _myFoo
{
    get { return _myFoo; }
    set { _myFoo = value; }
}

static ServiceLayer()
{
    _myFoo = new Service1Client();
}

      

If not, what is the difference between them?

Thank.

+3


source to share


3 answers


You need a support field because:

public static Service1Client _myFoo
{
    get { return _myFoo; }
}

      

.... like you will have a loop forever in your example.



However, C # does provide automatic properties. You can do the same with this simple code:

public static Service1Client MyFoo { get; set; }

static ServiceLayer()
{
    MyFoo = new Service1Client();
}

      

+9


source


Almost, but no. In your public domain, you cannot return the object you receive and install. You need a support box.

private static Service1Client _myFoo
public static Service1Client MyFoo
{
     get { return _myFoo; }
     set { _myFoo = value; }
}

      



In this case, since you are only doing basic get and set, you can use the auto property. This is equivalent to the above code.

public static Service1Client MyFoo { get; set; }

      

+3


source


Given this code:

public static Service1Client _myFoo
{
    get { return _myFoo; }
    set { _myFoo = value; }
}

      

You will get StackOverflowExcpetion

anytime you use a getter or setter because the setter is calling itself, which will call itself, etc. (until the stack space runs out).

One way to successfully shorten the first example would be:

public static Service1Client MyFoo {get;set;}

static ServiceLayer()
{
    MyFoo = new Service1Client();
}

      

+3


source







All Articles