1

Possible Duplicate:
Why use getters and setters?

I see this a fair bit in code examples...

private List<Car> cars;

public List<Car> Cars
   {
      get { return this.cars; }
      set { this.cars = value; }
   }

What's the benefit of that over just:

public List<Car> cars;

?

Thank you.

Community
  • 1
  • 1
Thomas Clayson
  • 29,657
  • 26
  • 147
  • 224
  • 2
    As an aside, you can use: `public List Cars { get; set; }` – Jackson Pope Oct 26 '11 at 14:30
  • You can add business logic to properties but for the above example where no logic is used you could use a simple public List Cars { get; set; } which will automatically generate the backing variable – Loman Oct 26 '11 at 14:38

2 Answers2

1

this is a property, a property allows you to control the set/get operations and perform other tasks when a value is set or get.

For example you could check if the cars list is null in the get and in case is null you can create and assign a new List to cars then return cars.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
1

Here are a couple of notable differences.

  • Several binding APIs will only consider Properties
  • Several serialization APIs will only consider Properties
  • Breakpoints can't be set on fields but can be set on properties
  • It's easier to version properties than fields
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 2
    Breakpoints are difficult to set on auto-properties though. – Adam Houldsworth Oct 26 '11 at 14:33
  • @AdamHouldsworth yes but you can always temporarily turn an auto-property into a full property for the purpose of debugging. The same is not true for fields. – JaredPar Oct 26 '11 at 14:34
  • definitely, I was just commenting for completion. I tend towards auto-properties / properties over public fields almost 100% of the time. Just noting because breaking an auto-property out when you are in a none standard situation (production / live code etc) is problematic. – Adam Houldsworth Oct 26 '11 at 14:35
  • @AdamHouldsworth: It's impossible to set a breakpoint on accessing a field (from the field side, of course), so I'm not sure how that's a distinction. – Adam Robinson Oct 26 '11 at 14:37
  • @AdamRobinson didn't say it was a distinction between auto-properties and fields, it was a distinction between auto-properties and properties. Auto-properties and properties are sometimes incorrectly seen as entirely synonymous, they aren't 100%. – Adam Houldsworth Oct 26 '11 at 14:38