Export (0) Print
Expand All
2 out of 2 rated this helpful - Rate this topic

Do not declare visible instance fields

TypeName

DoNotDeclareVisibleInstanceFields

CheckId

CA1051

Category

Microsoft.Design

Breaking Change

Breaking

An externally visible type has an externally visible instance field.

The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. Accessing a property is as easy as accessing a field, and the code in a property's accessors can change as the type's features expand without introducing breaking changes. Properties that just return the value of a private or internal field are optimized to perform on par with accessing a field; there is very little performance gain associated with using externally visible fields over properties.

Externally visible refers to public, protected, and protected internal (Public, Protected, and Protected Friend in Visual Basic) accessibility levels.

To fix a violation of this rule, make the field private or internal and expose it using an externally visible property.

Do not suppress a warning from this rule. Externally visible fields do not provide any benefits that are unavailable to properties. Additionally, public fields cannot be protected by Link Demands. See Secured types should not expose fields.

The following example shows a type (BadPublicInstanceFields) that violates this rule. GoodPublicInstanceFields shows the corrected code.

using System;

namespace DesignLibrary
{
   public class BadPublicInstanceFields
   {
      // Violates rule DoNotDeclareVisibleInstanceFields. 
      public int instanceData = 32;
   }

   public class GoodPublicInstanceFields
   {
      private int instanceData = 32;

      public int InstanceData
      {
         get { return instanceData; }
         set { instanceData = value ; }
      }
   }
}
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft. All rights reserved.