Do not declare visible instance fields
Expose data through properties rather than public fields.
Microsoft docsDescription
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
public class Point
{
public int X;
}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
refto modify fields, such as model-view-viewmodel (MVVM) frameworks for WPF and UWP.