Is there any situation where creating a field (apart from readonly, but only because language designers haven't implemented it for properties yet), are there situations where fields have any advantages over properties?
-
Respectfully, I don't agree that it's a duplicate. In context of this question, I understand the difference, and understand the numerous advantages of properties. However, after reading a lot of property/field debate, I came to idea that I must be missing something good about fields, and asked about this specific detail. Not the whole comparison. – Max Yankov Feb 07 '14 at 19:40
3 Answers
First of all you should remember that a Property, in .NET, is nothing more than just a syntactic sugar for 2 methods - one method for the property get section, and one for the property set section.
If you talk about public fields vs properties than the answer is: it is always better to use properties than public fields. Why? Because you achieve encapsulation which makes your code much more maintainable in the future.
If you talk about private fields vs properties than I would say: it is better to use private fields, because there is no reason to use properties in this case. There might be some exceptions though like for lazy loading:
private string _someField;
private string SomeProperty
{
get
{
if (_someField== null)
{
_someField= LoadData();
}
return _someField;
}
}

- 6,176
- 21
- 26
-
-
-
Yes, it would be obviously a better choice assuming that you work with .Net 4.5+ – Paweł Bejger Feb 07 '14 at 09:59
I tend to use fields for private and usually protected members, to make it explicit that this is just the state of the object and avoid the notational clutter.
I use properties for public members (and protected in big hierarchies), to get the typical benefits, like that I can change the behaviour later if I want to, have it on the interface, mock it later, etc.

- 35,875
- 47
- 158
- 240
One of my colleagues provided a good case when fields are more convenient:
float m_Time = 0;
Simple initialization of default values.

- 12,551
- 12
- 67
- 135
-
1But you can do the same with properties, just in this case you won't use the auto-implemented ones. – Paweł Bejger Feb 07 '14 at 09:48