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

444
Vistas
Convert String to ReadOnlyMemory<byte> in C#?

I would like to convert a String to a ReadOnlyMemory object. It's easy to convert a string to a ReadOnlyMemory object (using .AsMemory()) but there's no direct way to convert that to type byte, or directly convert the string otherwise.

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

0

The most straightforward way I found is by converting the string to a byte[] and returning that as ReadOnlyMemory, like so:

var memory = new ReadOnlyMemory<byte>(Encoding.UTF8.GetBytes(str));
over 4 years ago · Santiago Trujillo Denunciar

0

Thee is a way. The EncodingExtensions class contains GetBytes extension methods that can write to an IBuffeWriter< T>. Two built-in classes implement this interface, ArrayBufferWriter<> and PipeWriter.

In APIs that use System.IO.Pipelines it's better to write to a PipeWriter directly rather than create an intermediate object. I'll use ArrayBufferWriter instead, because ... it's easier. It still allows memory to be reused instead of allocating new buffers:

var text=".....";
var writer=new ArrayBufferWrite(8192);

Encoding.UTF8.GetBytes(text,writer);

var memory=writer.WrittenMemory;

WrittenMemoy returns a ReadOnlyMemory<T> object with the written data.

The buffer can be cleared with Reset() and reused :

var writer=new ArrayBufferWrite(8192);
while(true)
{
    writer.Reset();
    var text=SomehowGetString();
    
    Encoding.UTF8.GetBytes(text,writer);

    var memory=writer.WrittenMemory;
    ...
}
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