Skip to content

Instantly share code, notes, and snippets.

@richlander
Last active May 30, 2018 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richlander/5ac5cb13067c7c43355221d3e5078227 to your computer and use it in GitHub Desktop.
Save richlander/5ac5cb13067c7c43355221d3e5078227 to your computer and use it in GitHub Desktop.
Span<T> Slicing Example
// generating data for the example
int[] ints = new int[100];
for (var i = 0; i < ints.Length; i++)
{
ints[i] = i;
}
// creating span of array
Span<int> spanInts = ints;
// slicing the span, which creates another (subset) span
Span<int> slicedInts = spanInts.Slice(start: 42, length: 2);
// printing composition of the array and two spans
Console.WriteLine($"ints length: {ints.Length}");
Console.WriteLine($"spanInts length: {spanInts.Length}");
Console.WriteLine($"slicedInts length: {slicedInts.Length}");
Console.WriteLine("slicedInts contents");
for (var i = 0; i < slicedInts.Length; i++)
{
Console.WriteLine(slicedInts[i]);
}
// performing tests to validate the span has the expected contents
if (slicedInts[0] != 42) Console.WriteLine("error");
if (slicedInts[1] != 43) Console.WriteLine("error");
slicedInts[0] = 21300;
if (slicedInts[0] != ints[42]) Console.WriteLine("error");
// printing composition of subset span
Console.WriteLine("slicedInts contents");
for (var i = 0; i < slicedInts.Length; i++)
{
Console.WriteLine(slicedInts[i]);
}
@richlander
Copy link
Author

Run this code with .NET Core 2.1. You should see:

ints length: 100
spanInts length: 100
slicedInts length: 2
slicedInts contents
42
43
slicedInts contents
21300
43

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment