dotnet/roslyn

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

開放

#51,512 建立於 2021年2月26日

 (3 則留言) (1 個反應) (0 位負責人)C# (4,257 個分叉)batch import
Area-IDEIDE-CodeStylehelp wanted

倉庫指標

星標
 (20,414 顆星)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 256 個 PR)

描述

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.

貢獻者指南