Home
C#
Range (Array and List Syntax)
This page was last reviewed on Sep 25, 2024.
Dot Net Perls
Range. 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.
Array
List
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.
Example. 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.
int Array
Version 1 We can create a range and reference it with the Range struct type. This is not usually done, but it can be useful.
Version 2 Here we directly specify a range. We access elements from the int array with a range expression.
Version 3 If we omit the end index, we get all indexes until the end. Meanwhile if we omit the start index, we get all indexes starting at the first.
Version 4 With the caret "^" character, we count from the end. With a 0, we indicate the last index (zero places from the end).
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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 25, 2024 (image).
Home
Changes
© 2007-2024 Sam Allen.