Total .NET Analyzer Rule Documentation  

PublicField Rule

Avoid using public fields.

Remarks

A public field is a type exposed by a class that can be read or modified outside the class. For example, this Customer class exposes the Customer ID as a public field:


' VB
Class Customer
Public CustID As Integer
' Code here...
End Class

// C#
class customer
{
public int CustID;
}


In general, you should replace public fields with private fields, and use the Get and Set property accessors to expose the field. Public fields have many disadvantages, including:

1. With public fields, you cannot control access to the value (that is, read-only access vs. read/write access) without using a constant (which eliminates the class's ability to write to the value).

2. Public fields provide no way of attaching code execution to the reading or writing of the value. Often this can be an issue when your class needs to execute code internally to support access to a value.

3. Public fields do not allow your class to keep an internal representation of the original value for its own use. Since the class caller can change the value, the class cannot rely on the value at any point in code execution.

Resolution

Replace the public field with a private field, and use the Get and Set property accessors to expose the field. The following examples illustrate how to correctly use private fields:

' VB
Class Customer
Private CustID As Integer

Public Property CustInfo() As Integer
Get
Return CustID
End Get
Set(ByVal newCustID As Integer)
CustID = newCustID
End Set
End Property
End Class

//C#
class customer
{
private int custID;
public int custInfo
{
get
{
return custID;
}
set
{
custID = value;
}
}
}

See Also

Field Usage Guidelines