Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

439
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!