CA2011: Do not assign property within its setter

Property Value
Rule ID CA2011
Title Do not assign property within its setter
Category Reliability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As suggestion

Cause

A property was accidentally assigned a value within its own set accessor.

Rule description

Assigning a property to itself in its set accessor leads to an infinite chain of recursive calls to the set accessor. This results in a StackOverflowException at run time. Such a mistake is common when the property and the backing field to store the property value have similar names. Instead of assigning the value to the backing field, it was accidentally assigned to the property itself.

How to fix violations

To fix violations, replace the violating assignment to the property with either an assignment to the backing field or switch to using an auto-property. For example, the following code snippet shows a violation of the rule and a couple of ways to fix it:

public class C
{
    // Backing field for property 'P'
    private int p;

    public int P
    {
        get
        {
            return p;
        }
        set
        {
            // CA2011: Accidentally assigned to property, instead of the backing field.
            P = value;
        }
    }
}
public class C
{
    // Backing field for property 'P'
    private int _p;

    public int P
    {
        get
        {
            return _p;
        }
        set
        {
            // Option 1: Assign to backing field and rename the backing field for clarity.
            _p = value;
        }
    }
}
public class C
{
    // Option 2: Use auto-property.
    public int P { get; set; }
}

When to suppress warnings

It is fine to suppress violations from this rule if you are sure that the recursive calls to the set accessor are conditionally guarded to prevent infinite recursion.

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.

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

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

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

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

See also