Public fields in public classes do not respect the encapsulation principle and have three main disadvantages:
To prevent unauthorized modifications, private attributes and accessor methods (set and get) should be used.
Note that due to optimizations on simple properties, public fields provide only very little performance gain.
Public fields can be modified by any part of the code and this can lead to unexpected changes and hard-to-trace bugs.
Public fields don’t hide the implementation details. As a consequence, it is no longer possible to change how the data is stored internally without impacting the client code of the class.
The code is harder to maintain.
Fields marked as readonly or const are ignored by this rule.
Fields inside classes or structs annotated with the StructLayoutAttribute are ignored by this rule.
Depending on your needs:
readonly or const.
public class Foo
{
public int InstanceData = 32; // Noncompliant
public int AnotherInstanceData = 32; // Noncompliant
}
public class Foo
{
// using auto-implemented properties
public int InstanceData { get; set; } = 32;
// using field encapsulation
private int _anotherInstanceData = 32;
public int AnotherInstanceData
{
get { return _anotherInstanceData; }
set
{
// perform validation
_anotherInstanceData = value;
}
}
}
Please be aware that changing a field by a property in a software that uses serialization could lead to binary incompatibility.