Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

283
Vistas
How should I create an ImmutableArray from a Span/ReadOnlySpan?

Suppose I have a method like the following:

unsafe void Convert(byte* ptr, int length)
{
    var span = new Span<byte>(ptr, length);
    var arr = ImmutableArray.CreateRange(span); // error: cannot convert from 'System.Span<byte>' to 'System.Collections.Generic.IEnumerable<byte>'
    Use(arr);
}

The CreateRange method in the above sample is the CreateRange<T>(IEnumerable<T>) overload. Since Span doesn't implement any interfaces it makes sense that we can't make this call. But I am actually a bit stumped as to what to do instead. Is there some idiomatic way to create an ImmutableArray from a Span with minimal copying/allocation? (i.e. using Span<T>.ToArray() and then ImmutableArray<T>.ToImmutableArray() would not be ideal)

Would also appreciate any suggestions that involve using the pointer+length directly in some way.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

There is an open issue (as of June 2021) discussing adding APIs for this.

Until then, the issue suggests using a builder like this:

static ImmutableArray<T> ImmutableArrayFromSpan<T>(ReadOnlySpan<T> span)
{
    var builder = ImmutableArray.CreateBuilder<T>(span.Length);
    foreach (var i in span) {
        builder.Add(i);
    }
    return builder.MoveToImmutable();
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda