Home > Blockchain >  Why can't I assign a string to a ReadOnlySpan using .Net Framework 4.8?
Why can't I assign a string to a ReadOnlySpan using .Net Framework 4.8?

Time:10-04

I am trying to make use of ReadOnlySpan. I am trying to convert a guid variable to ReadOnlySpan like this:

ReadOnlySpan<char> newGuid = Guid.NewGuid().ToString();

But I get compile error

Cannot implicitly convert type string to System.ReadOnlySpan<char>

The ReadOnlySpan type comes from the System.Memory nuget package. How do I fix this?

CodePudding user response:

ReadOnlySpan (whether you get from the System.Memory package or from the runtime) only has implicit casts for arrays. So you need to turn your string into an array of chars first.

ReadOnlySpan<char> newGuid = Guid.NewGuid().ToString().ToCharArray();

In newer versions of .Net, like .Net 6, the string class has an implicit cast to ReadOnlySpan<char>, alleviating the need to turn your string into an array first.

  • Related