dotnet/roslyn

Code fix for CS1612 when assigning to a nested struct field or property

オープン

#51,512 opened on 2021/02/26

 (3 件のコメント) (1 件のリアクション) (0 人の担当者)C# (4,257 件のフォーク)batch import
Area-IDEIDE-CodeStylehelp wanted

Repository metrics

Stars
 (20,414 個のスター)
PR merge metrics
 (平均マージ 6d 17h) (30d で 256 merged PRs)

説明

It's not uncommon to write this code, then back up and realize you have to rewrite the entire assignment into three lines.

class C
{
    public S StructProperty { get; set; }

    void M()
    {
        /* ❌ CS1612 Cannot modify the return value of 'C.StructProperty' because it is not a variable
        ↓↓↓↓↓↓↓↓↓↓↓↓↓↓ */
        StructProperty.InnerProperty = 42;
    }
}

struct S
{
    public int InnerProperty { get; set; }
}

It would save me time if there was a light bulb fix 💡 Copy and set updated 'StructProperty' value:

        var structProperty = StructProperty;
        structProperty.InnerProperty = 42;
        StructProperty = structProperty;

I don't mind if it bails at a certain level of nesting because I rarely see such code, but there could be value in handling at least two struct properties at the end of the chain. (x.StructProperty.NestedStructProperty.Y = 42;)

This issue could be linked from the big table in https://github.com/dotnet/roslyn/issues/23326.

コントリビューターガイド