All rules
CA1051Design Enabled by default: No MS default: Warning

Do not declare visible instance fields

Expose data through properties rather than public fields.

Microsoft docs

Description

Public or protected instance fields break encapsulation. Use properties instead.

Cause

A type has a non-private instance field.

By default, this rule only looks at externally visible types, but this is configurable.

Why it matters

Properties allow validation, change tracking, and binary-compatible evolution that public fields do not.

How to fix violations

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

Examples

Avoid
public class Point
{
    public int X;
}
Prefer
public class Point
{
    public int X { get; set; }
}

When to suppress

Only suppress this warning if you're certain that consumers need direct access to the field. For most applications, exposed fields do not provide performance or maintainability benefits over properties.

Consumers may need field access in the following situations:

  • In ASP.NET Web Forms content controls.
  • When the target platform makes use of ref to modify fields, such as model-view-viewmodel (MVVM) frameworks for WPF and UWP.
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0