Why is this an issue?
Public fields in public classes do not respect the encapsulation principle and has three main disadvantages:
- Additional behavior such as validation cannot be added.
- The internal representation is exposed, and cannot be changed afterwards.
- Member values are subject to change from anywhere in the code and may not meet the programmer’s assumptions.
By using private fields and public properties (set and get), unauthorized modifications are prevented. Properties also benefit from additional
protection (security) features such as Link Demands.
Note that due to optimizations on simple properties, public fields provide only very little performance gain.
Noncompliant code example
public class Foo
{
public int instanceData = 32; // Noncompliant
}
Compliant solution
public class Foo
{
private int instanceData = 32;
public int InstanceData
{
get { return instanceData; }
set { instanceData = value ; }
}
}
Exceptions
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.
Resources