Skip to content

Never use mutable structs as in in argument - is it **Never** #13511

@gmanvel

Description

@gmanvel

Under the section Never use mutable structs as in in argument the reasoning is that in order to ensure readonly-ness of mutable structs passed using in modifier defensive copies had to be made.
This behavior doesn't seem to be consistent across different compiler versions.

If I use mutable struct, which is being passed with in modifier, with older versions of the compiler the defensive copy is indeed created. (sharplab.io)

However, same code with recent version of Roslyn, compiles to IL where defensive copy is not made. (sharplab.io)

If mutable struct uses non-auto-properties, then defensive copies are made regardless of compiler version. (sharplab.io)

Btw, I can see this behavior in .NET Core 2.1 app (C# 7.3) created in VS 2019.

Is there some kind of optimization in place when auto-properties are used ? Is this behavior documented anywhere ? If so can we refer to it ?


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Labels

    dotnet-csharp/svcneeds-more-infoNeeds more info from OP. Auto-closed after 2 weeks if no response. [org][resolution]

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status

    Active/Investigating

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions