private List _dates;
public List Dates
{
get { return _dates; }
set { _dates = value; }
}
OR
publi
I believe they compile to the same code. The latter is just syntactic sugar to represent the former. I tend to think of the latter as a placeholder for future logic that may need to be placed in the properties, at which point I'd convert said affected properties to the former.
Use the former if you need to add some kind of logic to your getter/setters.
Use the latter otherwise. It makes things much cleaner. You can also achieve read-only properties using auto properties:
public List<Date> Dates { get; private set; }
Or, if you don't want people to add any items to the list through the property you can resort to the former syntax:
private List<Date> _dates = new List<Date>();
private ReadOnlyCollection<Date> _readOnlyDates =
new ReadOnlyCollection<Date>(_dates);
public ReadOnlyCollection<Date> Dates
{
get { return _readOnlyDates; }
}
The two are compiled roughly the same way (I don't know that the backing field's name would specifically be the same, but they'd be functionally equivelant).
IIRC, the ability to do Automatic Properties (public List<Date> Dates {get; set;}
) was added in either .NET 3.0 or 3.5.
Both are basically the same because of how .NET compiles automatic properties. Automatic properties became available with .NET 3.5.
It doesn't matter. The second is just sugar. I always use the second because it's cleaner, but every once in a while I need access to the backing value.
They are equivalent in the internal compiled form, except that you cannot access the compiler generated private variable in the second form.
From a code efficiency point of view, they are equivalent as well, the just in time compiler normally directly accesses the private variable without the overhead of calling an access function (after the runtime environment has checked accessibility etc.).
From a coding perspective, I prefer the second version which is more compact (less to write, less to read).
The second syntax was introduced in C# 3.0. So the first variant would be more compatible to old compilers.