Ranges with Arrays and Strings
Slice arrays, spans, and substrings.
Slicing Arrays
The most common use of ranges is slicing arrays. array[1..3] returns a new array containing the selected elements.
using System;
int[] data = { 10, 20, 30, 40, 50 };
int[] middle = data[1..3];
Console.WriteLine(string.Join(",", middle)); // 20,30Array Slices Are Copies
For arrays, a range slice allocates a new array and copies the elements. Mutating the slice does not affect the original.
using System;
int[] original = { 1, 2, 3, 4 };
int[] slice = original[0..2];
slice[0] = 99;
Console.WriteLine(original[0]); // 1 (unchanged)
Console.WriteLine(slice[0]); // 99All lessons in this course
- The Index Type and ^ Operator
- The Range Type and .. Operator
- Ranges with Arrays and Strings
- Custom Types Supporting Ranges