Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 986
Mario Vernari Avatar asked Mar 26 '26 18:03

Mario Vernari


1 Answers

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:

  • Resolve errors and warnings in constructor declarations: Primary constructor declaration
like image 146
Guru Stron Avatar answered Mar 29 '26 06:03

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!