dotnet/roslyn

Unnecessary defensive copies in `string` + implicit `object` operator

Open

#72.044 geöffnet am 10. Feb. 2024

Auf GitHub ansehen
 (0 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)C# (4.257 Forks)batch import
Area-CompilersBughelp wanted

Repository-Metriken

Stars
 (20.414 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 6T 17h) (256 gemergte PRs in 30 T)

Beschreibung

When string + something (not a string) is encountered, the compiler converts the something to a string using the ToString method, instead of boxing it. However, it does not currently recognise that defensive copies are unnecessary if the ToString method is marked readonly.

Version Used:

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

Steps to Reproduce:

using System;
public class C
{
    public static string M1(in S1 s)
    {
        return "" + s; //defensive copy (unnecessary)
    }

    public static string M2(ref S1 s)
    {
        return "" + s; //no defensive copy
    }
}
public struct S1
{
    public readonly override string ToString() => "";
}

Link

Expected Behavior:

s.ToString() is emitted without a defensive copy of s in both cases, since the method is marked as readonly.

Actual Behavior:

s.ToString() is emitted with a defensive copy of s in M1.

Contributor Guide