Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading