Menu

Stop Copying a String Into a MemoryStream. .NET 11 Has StringStream
📰

Stop Copying a String Into a MemoryStream. .NET 11 Has StringStream

DEV Community: dotnet·JKC·8 days ago
#Bj0CUGzP
#devtodotnet#devto#dev#stream#stringstream
Reading 0:00
15s threshold

TL;DR: .NET 11 adds StringStream , ReadOnlyMemoryStream , and WritableMemoryStream . They wrap a string , a ReadOnlyMemory<byte> , or a Memory<byte> as a Stream , so you stop copying data into a MemoryStream just to satisfy a method signature.

This ships in .NET 11, which is at Release Candidate 2 with a go-live license, but is not GA yet. Everything below was run on the .NET 11 RC 1 SDK.

The line everybody has written

Some API wants a Stream . You have a string . So you write the line that has been in every codebase since 2002:

using var stream = new MemoryStream ( Encoding . UTF8 . GetBytes ( text ));

Enter fullscreen mode

Exit fullscreen mode

It works. It also encodes the entire string into a brand new byte[] before the parser reads a single byte.

The same story repeats with buffers. You already have a ReadOnlyMemory<byte> from a pool, a socket, or a slice, and the only way to hand it to a Stream API was to call ToArray() and copy it, or write your own little wrapper class.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.