Skip to content

Preview version of C# language uses incorrect constructor overloading for arrays #210

@nsentinel

Description

@nsentinel

Thanks for the great library!


First-class Span Types is currently under development. Recent changes, in particular Prefer converting T[] to ReadOnlySpan over Span in overload resolution, also affect the library.

See the following code for an example:

using System;
using System.Buffers;

class Program {
    static void Main()
    {
        S(ArrayPool<char>.Shared.Rent(16));
        S("abc");
    }

    static void S(Span<char> _) => Console.WriteLine("Span");
    static void S(ReadOnlySpan<char> _) => Console.WriteLine("ReadOnlySpan");
}

Old behavior vs New behavior

That is, by default, it's now easy to get into an invalid constructor overload when passing a buffer from an array. This is not something that will happen sometime in the future, to get problems you just need to enable the preview version of the language for .NET 9. For example, interesting issues: 1, 2


To resolve this issue, all you need to do now is add the OverloadResolutionPriority attribute

using System;
using System.Buffers;
using System.Runtime.CompilerServices;

class Program {
    static void Main()
    {
        S(ArrayPool<char>.Shared.Rent(16));
        S("abc");
    }

    [OverloadResolutionPriority(1)]
    static void S(Span<char> _) => Console.WriteLine("Span");
    static void S(ReadOnlySpan<char> _) => Console.WriteLine("ReadOnlySpan");
}

Demo


It might be more correct to remove overloading with ReadOnlySpan<char>, for example by adding a static method to create a ValueStringBuilder from a given buffer. For example, .NET without it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions