-1

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;}
}
Peter
  • 27,590
  • 8
  • 64
  • 84
  • 2
    Please define _'more "true"'_. Anyway, duplicate of the above and many others, opinion-based, and so on. :) – CodeCaster Dec 10 '13 at 08:49

4 Answers4

1

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).

nphx
  • 1,426
  • 3
  • 19
  • 30
1

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

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

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.

Justin
  • 84,773
  • 49
  • 224
  • 367
0

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).

Jay
  • 9,561
  • 7
  • 51
  • 72