Search code examples
c#.netvisual-studiomemory-management

MsCorLib Array.cs Array.Sort line of code that not compile


in th MsCorLib Array.cs source file there is the following Method, at line 1941:

void Sort<T>(T[] array)

in the body block at line 1948 there is the followin line

var span = new Span<T>(ref MemoryMarshal.GetArrayDataReference(array), array.Length);

if i try to copy paste this line on a my project, with C# 11 and .NET 7, there is a compile error "Argument 1 may not be passed with 'ref' keyword"

How is possible this? Waht i have to do to compile this line?

enter image description here


Solution

  • It uses internal Span<T> constructor which is not publicly available:

    #pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228
    // Constructor for internal use only. 
    // It is not safe to expose publicly, 
    // and is instead exposed via the unsafe MemoryMarshal.CreateSpan.
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    internal Span(ref T reference, int length)
    {
        Debug.Assert(length >= 0);
     
        _reference = ref reference;
        _length = length;
    }
    #pragma warning restore IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228
    

    So "outside" compiler has only ctor with 2 parameters available - Span<T>(Void*, Int32) which requires pointer, not a ref parameter, hence the compilation error.

    As mentioned in the comment in the source - you can use MemoryMarshal.CreateSpan as a substitute.