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

Viewed 27158

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

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

You need to install the System.Memory NuGet package.

There are extension methods for strings called .AsSpan() or .AsReadOnlySpan() to convert a string to the appropriate Span<T>.

Example:

Span<char> mySpan = "My sample source string".AsSpan();
ReadOnlySpan<char> myReadOnlySpan = "My read only string".AsReadOnlySpan();

Source: MSDN Channel 9 "C# 7.2: Understanding Span" (around the 6 minute mark)

Update: this answer was correct at the time, but based on a preview version. See updated answer on this page by gfoidl for current procedure.

Provided you are on .NET Core/5+ or have the NuGet packages installed (see other answers), you can create a Span<char> from string as so:

string str = "My sample source string";
Span<char> mySpan = stackalloc char[str.Length]; // or `new char[str.Length]`
str.AsSpan().CopyTo(mySpan);
Related