41 lines
1.2 KiB
Plaintext
41 lines
1.2 KiB
Plaintext
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 <code>readonly</code> or <code>const</code> are ignored by this rule.
|
|
Fields inside classes or structs annotated with the <code>StructLayoutAttribute</code> are ignored by this rule.
|
|
|
|
include::../see.adoc[]
|