Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

445
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda