-1

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?

Community
  • 1
  • 1
Max Yankov
  • 12,551
  • 12
  • 67
  • 135
  • 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 Answers3

2

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;
    }
}
Paweł Bejger
  • 6,176
  • 21
  • 26
1

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.

Grzenio
  • 35,875
  • 47
  • 158
  • 240
0

One of my colleagues provided a good case when fields are more convenient:

float m_Time = 0;

Simple initialization of default values.

Max Yankov
  • 12,551
  • 12
  • 67
  • 135