How do I convert a C# string to a Span<char>? (Span<T>)

Dan Sorensen picture Dan Sorensen · Nov 16, 2017 · Viewed 19.7k times · Source

How do I convert a string to a Span<T>?

Span<char> mySpan = "My sample source string";

Answer

gfoidl picture gfoidl · Mar 23, 2018

Span<T> and friends are included in .NET Core 2.1, so no additional NuGet package needs to be installed.

Dan Sorensen's answer was correct at that date and based on the preview, but now it is outdated. For string, the extension methods are AsSpan and AsMemory, that return ReadOnlySpan<char> and ReadOnlyMemory<char> respectively.

Explicit AsReadOnlySpan is gone, because strings are immutable, so it makes no sense to get back a Span<char> (that is writeable).