Do not assign property within its setter
Do not assign property within its setter
Microsoft docsDescription
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 System.StackOverflowException at runtime. 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.
Cause
A property was accidentally assigned a value within its own set accessor.
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:
Example
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;
}
}
}When to suppress
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.