Properties with or without private fields

940 views Asked by At

What is more "true": use properties with or without private fields. I.e.

1.

class A
{
    int _field;
    public int Field
    {
        get{ return _field;}
        set{_field = value;}
    }
}

2.

class A
{
    public int Field{get;private set;}
}
4

There are 4 answers

0
nphx On

Number 2 creates a backing field automatically, so you always have a private field "behind the scenes" (although not directly accessible in the latter case).

0
Guru Stron On

when you create anonymous property compiler creates corresponding field for you, so it's pretty much the same, but you can access autocreated field only via property

0
Justin On

It makes no difference - the compiler generates the property implementation for you in exactly the same way that it generates a default constructor or the code for a using statement. These two classes are nearly 100% equivalent which you can see if you decompile an auto-property (the only difference is the name of the generated backing field that the compiler uses)

class A
{
    public int Field {get; private set;}
}

class A
{
    int _field;
    public int Field
    {
        get { return _field; }
        private set {_field = value; }
    }
}

Its completely down to your personal preference.

0
Jay On

As has already been stated, the second creates the backing field at compile time. You would typically define a backing field your self if you wanted the property to act as a public accessor to the field, where you can add custom logic or prevent the value being modified (using the private keyword on the setter).