dotnet/roslyn

Code fix for CS0206 when passing a property to a ref parameter

Open

#51,515 opened on Feb 26, 2021

View on GitHub
 (6 comments) (0 reactions) (0 assignees)C# (4,257 forks)batch import
Area-IDEConcept-Continuous ImprovementIDE-CodeStylehelp wanted

Repository metrics

Stars
 (20,414 stars)
PR merge metrics
 (Avg merge 6d 17h) (256 merged PRs in 30d)

Description

This is similar to https://github.com/dotnet/roslyn/issues/51512 and could also be linked from the big table in https://github.com/dotnet/roslyn/issues/23326 under CS0206, and CS1510 for the last example.

class C
{
    public int Property { get; set; }

    void M()
    {
        // ❌ CS0206 A property or indexer may not be passed as an out or ref parameter
        //     ↓↓↓↓↓↓↓↓
        M2(ref Property);
    }

    void M2(ref int p) { }
}

It would save me time if there was a light bulb fix 💡 Pass and update 'Property' using a temporary variable:

        var property = Property;
        M2(ref property);
        Property = property;

out parameters

        M2(out Property);

💡 Update 'Property' using a temporary variable:

        M2(out var property);
        Property = property;

Struct properties

https://github.com/dotnet/roslyn/issues/51512 comes into play and ideally these two concepts would work together.

        M2(ref StructProperty.InnerProperty);

💡 Copy and set updated 'StructProperty' value (message from https://github.com/dotnet/roslyn/issues/51512):

        var structProperty = StructProperty;
        var innerProperty = structProperty.InnerProperty;
        M2(ref innerProperty);
        structProperty.InnerProperty = innerProperty ;
        StructProperty = structProperty;

With an out parameter:

        M2(out StructProperty.InnerProperty);

💡 Copy and set updated 'StructProperty' value (message from https://github.com/dotnet/roslyn/issues/51512):

        M2(out var innerProperty);
        var structProperty = StructProperty;
        structProperty.InnerProperty = innerProperty;
        StructProperty = structProperty;

Non-lvalues (CS1510)

@RikkiGibson suggested that this could be extended to provide a fix for passing a ref to a non-lvalue for a different error code, CS1510:

        // ❌ CS1510 A ref or out value must be an assignable variable
        //      ↓↓↓↓↓
        M2(ref (2 + 2));

💡 Pass '2 + 2' using a temporary variable (stripping the parens in the message):

        var suggestedName = 2 + 2;
        M2(ref suggestedName)

Contributor guide