C#idiomatic C#
ca1823fundamentals/code-analysis/quality-rules

Code analysis

CA1823: Avoid unused private fields

Learn about code analysis rule CA1823: Avoid unused private fields

CA1823 Performance enabled by default in .NET 10: No
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

This rule is reported when a private field exists in your code but is not used by any code path.

Rule description

Private fields were detected that do not appear to be accessed in the assembly.

How to fix violations

To fix a violation of this rule, remove the field or add code that uses it.

Example

sample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1823.cssnippet1

csharp
namespace ca1823
{
    //<snippet1>
    public class User
    {
        private readonly string _firstName;
        private readonly string _lastName;

        // CA1823: Unused field '_age'
        private readonly int _age;

        public User(string firstName, string lastName)
        {
            _firstName = firstName;
            _lastName = lastName;
        }

        public string GetFullName()
        {
            return $"My name is {_firstName} {_lastName}";
        }
    }
    //</snippet1>
}

When to suppress warnings

It is safe to suppress a warning from this rule.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable CA1823
// The code that's violating the rule is on this line.
#pragma warning restore CA1823

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA1823.severity = none

For more information, see How to suppress code analysis warnings.