Search code examples
c#c#-12.0primary-constructor

Warning in property initialization in class with primary constructor


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?


Solution

  • This happens because compiler will generate one backing field for a used in Sum and another backing field for auto-property A.

    Note that a is mutable, while A is not hence you can do:

    public void MutateA(int i) => a += i;
    

    Which will affect Sum but will not affect A:

    C c = new C(42);
    c.MutateA(7);
    Console.WriteLine(c.A); // Prints 42
    Console.WriteLine(c.Sum(0)); // Prints 49
    
    public sealed class C(int a)
    {
        public int A { get; } = a;  //<--here
    
        public int Sum(int b)
        {
            return a + b;
        }
    
        public void MutateA(int i) => a += i;
    }
    

    The workaround/fix would be to use A instead of a in the Sum:

    public int Sum(int b) =>  A + b;
    

    See also: