Skip to content

String concatenation drops Span<char>.ToString() and does not recompile (CS0019) #3895

Description

@sailro

Summary

ILSpy removes an explicit ToString() call from a Span<char> operand when reconstructing
string concatenation. Unlike ordinary value types, a byref-like type cannot be converted to
object for the built-in string concatenation operator, so the resulting C# does not compile.

Input code

Compiled in Release targeting .NET 8.0 with C# 12:

using System;

public static class C
{
    public static string M(Span<char> span) =>
        "prefix" + span.ToString();
}

Erroneous output

using System;

public static class C
{
    public static string M(Span<char> span)
    {
        return "prefix" + span;
    }
}

Recompiling this output fails:

error CS0019: Operator '+' cannot be applied to operands of type 'string' and 'Span<char>'

Expected output

The explicit call must be retained:

return "prefix" + span.ToString();

Details

  • Product in use: ICSharpCode.Decompiler
  • Version in use: master 7554c1b0 (11.0.0.9223)
  • The repro was verified in an isolated compile, decompile, recompile round trip.
  • With string-concatenation reconstruction disabled, ILSpy correctly emits string.Concat("prefix", span.ToString()).
  • RemoveRedundantToStringInConcat assumes that the built-in operator can reproduce the removed call, but that is not true for byref-like values.
  • I am happy to contribute a fix.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions