Crash-Course: Spans in C#

Herman Schoenfeld
1 min readJul 19, 2020

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.

Fingers hurt from clicking all day? Try Auto Mouse.

Want to use Notion as a CMS for your website? Try Local Notion.

  1. Arrays implicitly casts to spans

byte[] byteArr = …;

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

NOTE
- 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)

become

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: https://docs.microsoft.com/en-us/archive/msdn-magazine/2018/january/csharp-all-about-span-exploring-a-new-net-mainstay

--

--

Herman Schoenfeld

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