Last active
May 30, 2018 00:57
-
-
Save richlander/5ac5cb13067c7c43355221d3e5078227 to your computer and use it in GitHub Desktop.
Span<T> Slicing Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run this code with .NET Core 2.1. You should see: