First of all, I have read the question asking for the difference between fields and properties and I know what it is used for.
Now on to my question, I wanted to create a property where I am sure that get and set will both be empty, so I do get; set;
. All good and well. But now I realised that I have just made a public field with a capital name, it is in all ways identical.
Even the argument of it being used so future code does not depend on implementation cannot be said, as I can simply make this a property and implement a getter or a setter. The semantics of a field and a property are identical outside the class it is defined in.
So my question is, should I use a field or a property when a property would simply use get;set;
?
So this:
public IEnumerable<string> Products;
is identical in all ways to this:
public IEnumerable<string> Products { get; set; }
should I use a field or a property when a property would simply use get;set;?
Use a property... for the practical reasons below, and for the philosophical reasons that properties expose a state API, whereas fields expose a state implementation detail.
The semantics of a field and a property are identical outside the class it is defined in.
That's not true.
SomeMethod(ref x.Products)
will become invalid when Products
becomes a property.)foo.Location.X = 10
works when Location
is a field (because x.Location
is classified as a variable) whereas it doesn't when Location
is a property (because then the expression x.Location
is classified as a value). If you have a method (in your evil mutable type) which mutates the value instead, then foo.Location.DoSomething()
will compile in both cases, but have a different effect. Fun for all the family.See more on this question at Stackoverflow