Search code examples
c#memory.net-core

How do I create a Span<T> of length 1 over a single variable (field or ref parameter) of type T


This question is regarding types Span<T> and RealOnlySpan<T> in .NET Core. The documentation explains how to create a span over an array, or an array segment, or a stack-allocated or unmanaged memory. In some circumstances I would like to create a span of length 1 over a single variable (a field, a ref parameter, or ref local) to pass it to API that can deal with arbitrary spans. How can I do that?

I imagine there could be a constructor Span<T>.Span(ref T), but apparently there isn't one. Copying the variable into an array and creating a span over that array does not solve the problem, because any modifications of the span would not reflect on the original variable.


Solution

  • MemoryMarshal.CreateSpan<T>(ref T reference, int length)
    

    Passing 1 in as the length argument. Note, this is inherently unsafe* which is why its in the System.Runtime.InteropServices namespace.

    *Its not checked for validity in anyway, if the length is too long you will overwrite other memory, if you return the span from a method and its a local variable you are in trouble etc.