Type Casting using Span<T>

In an earlier post, we explored the possibilities of Span and performance benefits of the feature was clearly visible in our benchmark tests. We will continue exploring the Span further in this post, as attempt to cast between types using Span.

The cast functionality is not that hard, thanks to the extension methods that comes along with Span<byte> under the System.MemoryExtensions namespace. The NonPortableCast method converts a Span<byte> to the specified Type.  As seen in the code below, the first step however is to convert the original type to a byte array. The implicit conversion between byte array and Span<byte> would allow you to convert it to Span<byte>.

 

long originalPrimitiveType = 25;
Span byteSpan = BitConverter.GetBytes(originalPrimitiveType);
Span intSpan = byteSpan.NonPortableCast();
int castPrimitiveType = intSpan[0];
The key point to note here is the first 4 bytes of Span<byte> maps to the zeroth element of Span<int>. The code samples described in this post is available in my Github.