Do you use Public/Protected Properties instead of Public/Protected Fields?
  v1.0 Posted at 26/04/2018 7:49 AM by Tiago Araujo

Public/Protected properties have a number of advantages over public/protected fields:

  • Data validation
    Data validation can be performed in the get/set accessors of a public property. This is especially important when working with the Visual Studio .NET Designer.
  • Increased flexibility
    Properties conceal the data storage mechanism from the user, resulting in less broken code when the class is upgraded. Properties are a recommended object-oriented practice for this reason.
  • Compatibility with data binding
    You can only bind to a public property, not a field.
  • Minimal performance overhead
    The performance overhead for public properties is trivial. In some situations, public fields can actually have inferior performance to public properties.​

​public int Count;

Figure: Bad code. Variable declared as a Field

public int Count
return _count;
_count = value;

Figure: Good code. Variable declared as a Property​​

We agree that the syntax is tedious and think Microsoft should improve this.

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address: