C# 8 introduces two new classes in the form of System.Index and System.Range that represent a single index and a range of indices respectively. These let you access a range of elements in a collection and when used in conjunction with Span<T>
and Memory<T>
can provide high-performance access to arrays and other in-memory structures.
In order to make the range and index classes more readable, two new operators were introduced: ..
for a range of indices and ^
for an index from the end of the collection.
Code
C#
var fullList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int lastItem = fullList[^1];
List<int> firstThreeItems = fullList[..3];
List<int> aSubset = fullList[3..7];
C#
var fullList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int lastItem = fullList[fullList.Count - 1];
List<int> firstThreeItems = fullList.Take(3).ToList();
List<int> aSubset = fullList.Skip(3).Take(4).ToList();