c# Static Class Property

20,885

Solution 1

You need the backing field because:

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

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

However, C# does provide automatic properties. You could accomplish the same thing with this simple code:

public static Service1Client MyFoo { get; set; }

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

Solution 2

Given this code:

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

You will get a StackOverflowExcpetion any time you use the getter or the setter because the setter calls itself, which will call itself, etc (until you run out of stack space).

One way of successfully shortening the first example would be:

public static Service1Client MyFoo {get;set;}

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

Solution 3

Almost, but no. In your public property, you can't return the object you're getting and setting. You need a backing field.

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

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

public static Service1Client MyFoo { get; set; }
Share:
20,885
Riddick
Author by

Riddick

Systems Development Analyst with a passion for learning, collaborating, sharing and helping!

Updated on July 22, 2020

Comments

  • Riddick
    Riddick almost 4 years

    An example has been shown to me today, and just wanted to check if both of the following will in fact have the same effect, and it not, what the difference is between them.

    Is this:

    private static Service1Client _myFoo;
    
    static ServiceLayer()
    {
        MyFoo = new Service1Client();
    }
    
    public static Service1Client MyFoo
    {
        get { return _myFoo; }
        set { _myFoo = value; }
    }
    

    Just a long winded way of doing this:

    public static Service1Client _myFoo
    {
        get { return _myFoo; }
        set { _myFoo = value; }
    }
    
    static ServiceLayer()
    {
        _myFoo = new Service1Client();
    }
    

    If this isn't the case, what is the difference between them?

    Thanks.

  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen over 11 years
    You will get a StackOverflowExcpetion any time you use the getter or the setter Just to be pendantic: If you build in Release mode, you won't [always?] get a stack overflow, "just" an infinite loop. That's probably because of some tail call elimination or similar optimization.