Updated Span API : NonPortableCast and AsReadOnlySpan to MemoryMarshal.Cast and AsSpan

One of the interesting changes (not sure why Microsoft changed this) was moving/changing the Span<T> API’s a bit. For example, the Span<T>.NonPortableCast Method was moved as an extension method under MemoryMarshal.

Previous API

Span<byte> byteSpan = BitConverter.GetBytes(originalPrimitiveType);
Span<int> intSpan = byteSpan.NonPortableCast<byte, int>();

Current API

Span<byte> byteSpan = BitConverter.GetBytes(originalPrimitiveType);
Span<int> intSpan = MemoryMarshal.Cast<byte, int>(byteSpan);

Similarly, the string.AsReadonlySpan method has been renamed. The new API is as follows.

Previous API

ReadOnlySpan<char> keyString = "SomeText".AsReadOnlySpan();

Current API

ReadOnlySpan<char> keyString = "SomeText".AsSpan();

The MemoryMarshal extensions can be found under the System.Runtime.InteropServices namespace. Code discussed in my earlier post about Benchmarking Span has been updated in my Github.