Riddick
Riddick

Reputation: 1318

c# Static Class Property

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.

Upvotes: 6

Views: 26570

Answers (3)

Servy
Servy

Reputation: 203802

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();
}

Upvotes: 3

Dave Zych
Dave Zych

Reputation: 21887

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; }

Upvotes: 3

itsme86
itsme86

Reputation: 19486

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();
}

Upvotes: 10

Related Questions