Modern versions of the C# language support Range syntax. We can specify a range of indexes and then access an array or List
with that range.
With two dots, we indicate we want all indexes between the first and second numbers. We can also specify "all indexes" from the start or the end.
Here we create 4 ranges that all cover the same indexes in the array. We skip over the first element, but include the second, third and fourth (final) indexes.
struct
type. This is not usually done, but it can be useful.int
array with a range expression.using System; int[] values = [0, 1, 600, 610]; // Version 1: create a range. Range r = 1..values.Length; int[] test0 = values[r]; foreach (int v in test0) { Console.WriteLine($"test0: {v}"); } // Version 2: use indexes from the end with caret. int[] test1 = values[1..values.Length]; foreach (int v in test1) { Console.WriteLine($"test1: {v}"); } // Version 3: omit end index to get maximum value. int[] test2 = values[1..]; foreach (int v in test2) { Console.WriteLine($"test2: {v}"); } // Version 4: use "from end" syntax with caret. int[] test3 = values[1..^0]; foreach (int v in test3) { Console.WriteLine($"test3: {v}"); }test0: 1 test0: 600 test0: 610 test1: 1 test1: 600 test1: 610 test2: 1 test2: 600 test2: 610 test3: 1 test3: 600 test3: 610
Ranges are useful when accessing elements from arrays and Lists. We can use the modern range syntax to simplify programs that access elements from within these linear collections.