Roslyn: C# 9 Records: Explicit property declaration breaks primary constructor

Created on 14 Oct 2020  路  7Comments  路  Source: dotnet/roslyn

Version Used: 3.8.0-3.20458.6

Steps to Reproduce:

Run the following code:

Console.WriteLine (new Test(1).X == 1);

record Test (int X)
{
    int _x;
    public int X { get => _x; init => _x = value; }
}

Expected Behavior:

This should print "True"

Actual Behavior:

It prints "False"

The auto-generated constructor fails to set the X property.

4 - In Review Area-Compilers Bug Concept-Diagnostic Clarity

Most helpful comment

A warning on unused ctor arguments seems reasonable.

All 7 comments

When you redefine the property you're responsible for the assignment as well.

record Test (int X)
{
    int _x = X; // <--
    public int X { get => _x; init => _x = value; }
}

Can I suggest that Roslyn reports a warning when a record's positional parameter is unused? That would catch cases where the user assumes that a positional parameter's value will be used to initialise some member, but this isn't actually the case.

Can I suggest that Roslyn reports a warning when a record's positional parameter is unused?

That's similar to https://github.com/dotnet/roslyn/issues/47677, both a good candidate for warning waves.

Why would this be a candidate for a warning wave? Records haven't been released yet, so there's surely no backwards compat concern with adding a warning to records now?

I personally agree with @canton7. This should be something to address as a regular warning before the final release.

A warning on unused ctor arguments seems reasonable.

Discussion from closed PR https://github.com/dotnet/roslyn/pull/47675 may be useful for reference.

Was this page helpful?
0 / 5 - 0 ratings