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.
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 start or end index, we get all indexes until the furthest valid index.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 11, 2025 (edit).