Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of C# properties

private List<Date> _dates;

public List<Date> Dates
{
    get { return _dates; }
    set { _dates = value; }
}

OR

public List<Date> Dates
{
    get;        
    set;    
}

I have always used the former, is that incorrect or bad practice? It never occurred to me that I could just use the second option. I do like having my encapsulated variables to begin with an underscore so I can distinguish them from method parameters. And I've just always done it that way.

Is it possible that using the first option would result in an extra List<Date> object being instantiated and then the whole of _dates being replaced with value, or is it more intelligent than that?

Also, which is the most prominent in industry or is it totally subjective?

like image 206
Nobody Avatar asked Aug 20 '10 14:08

Nobody


People also ask

How do you use circa C?

Use circa or an abbreviation of circa, if you are not certain of the exact year the house was built. Use circa or an abbreviation of circa when the date ends in a zero, 1870 for example.

How do you denote circa?

circa. Circa, which translates as “around” or “approximately,” usually appears with dates. You may see it abbreviated as c. or ca. (or, more rarely, as cca. or cir.).

What is the C before a date?

Often dates will be preceded with a "c." or a "ca." These are abbreviations of the Latin word "circa" which means around, or approximately. We use this before a date to indicate that we do not know exactly when something happened, so c. 400 B.C.E. means approximately 400 years Before the Common Era.

Does C mean circa?

Circa is Latin for "around" or "about". It is often used to show when something approximately happened. It is often shortened to c., ca., ca or cca.


1 Answers

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; }
}
like image 103
Justin Niessner Avatar answered Sep 28 '22 08:09

Justin Niessner