Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 951
Riddick Avatar asked Jan 24 '13 18:01

Riddick


1 Answers

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();
}
like image 124
itsme86 Avatar answered Sep 22 '22 14:09

itsme86