Spans are special structs in .NET Core designed to provide pointer-like constructs in safe, managed contexts. This allows array and buffer manipulation similar to how how they’re done in C++, C and Pascal and with comparable performance.

  1. Arrays implicitly casts to spans

byte[] byteArr = …;

// implicit cast
ReadOnlySpan<byte> span = byteArr;
Span<byte> span2 = byteArr;

- use ReadOnlySpan if you never need to change a value
- only use Span if you need to change a value

2. Spans encapsulate “offset and length” as a well as pointer. Thus method signatures like:

void SomeMethod(byte[] arr, int offset, int length)

SomeMethod(myArr, myOffset, myLength)


void SomeMethod(ReadOnlySpan<byte> arr)

SomeMethod(myArr.AsSpan(myOffset, myLength))

To get a sub-span within a span, use

mySpan.Slice(newOffset, newLength)
myArray.AsSpan(newOffset, newLength)

Length argument can be omitted and inferred as the remainer of the array after offset.

mySpan.Slice(newOffset); // from newOffset to end of
myArr.AsSpan(1); // this gets everything after first byte

3. In unsafe contexts,to get byte* of a span, use

byte *p = &mySpan.GetPinnableReference();

Learn more at:

Developer at PascalCoin, Inventor of RandomHash, Developer of, Founder & CEO of PascalCoin Foundation, Director of Sphere 10 Software.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store