C# Automatic Properties

Gavin picture Gavin · Aug 18, 2009 · Viewed 20.6k times · Source

I'm a bit confused on the point of Automatic properties in C# e.g

public string Forename{ get; set; }

I get that you are saving code by not having to declare a private variable, but what's the point of a property when you are not using any get or set logic? Why not just use

public string Forename; 

I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?

Answer

MatthewMartin picture MatthewMartin · Aug 18, 2009

Properties can have code put into them without breaking contract, fields can't have code put into them without changing them to properties (and breaking the interface). Properties can be read only or write only, fields can't. Properties can be data bound, fields can't.