I noticed that a snippet like the below one, it marks the property initialization with a warning.
public sealed class C(int a)
{
public int A { get; } = a; //<--here
public int Sum(int b)
{
return a + b;
}
}
The warning says:
warning CS9124: Parameter 'int a' is captured into the state of the enclosing type and its value is also used to initialize a field, property, or event.
However, if I omit any further a variable usage, the warning disappears.
public sealed class C(int a)
{
public int A { get; } = a;
public int Sum(int b)
{
return b; //<-- no more 'a' used here
}
}
Now, it is not very clear to me the reason of the warning, although I have a suspect. Is it because any a modification in the class will not change the A property, in this case?
This happens because compiler will generate one backing field for
aused inSumand another backing field for auto-propertyA.Note that
ais mutable, whileAis not hence you can do:Which will affect
Sumbut will not affectA:The workaround/fix would be to use
Ainstead ofain theSum:See also: