dotnet/roslyn

Unnecessary defensive copies on enums passed by `in`

Open

#72,016 opened on Feb 9, 2024

View on GitHub
 (4 comments) (0 reactions) (0 assignees)C# (4,257 forks)batch import
Area-CompilersBughelp wanted

Repository metrics

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

Description

The compiler emits unnecessary defensive copies on enums passed by in.

Version Used:

Sharplab.io Also reproduces with the compiler included in the .NET 8.0.100 SDK

Steps to Reproduce:

using System;
public class C
{
    public void M<T1, T2>(in Enum1 value1, ref Enum1 value2, Enum1 value3, in T1 value4, in T2 value5) where T1 : Enum where T2 : struct, Enum
    {
        value1.ToString(); //defensive copy (unnecessary)
        value2.ToString(); //no defensive copy
        value3.ToString(); //no defensive copy
        value4.ToString(); //defensive copy (unnecessary)
        value5.ToString(); //defensive copy (unnecessary)
    }
}
public enum Enum1
{
}

Link

Expected Behavior:

None of the calls to .ToString() emit a defensive copy, since none is required for any of them.

Actual Behavior:

value1.ToString() emits a defensive copy, and similar for value4 and value5.

Contributor guide