csharp / intermediate
Snippet
Array Manipulation using Indices and Ranges
Indices (^ operator) and Ranges (.. operator) provide a concise syntax for accessing elements from the end of an array or extracting sub-sections.
snippet.cs
csharp
1
2
3
4
5
6
7
int[] numbers = { 10, 20, 30, 40, 50, 60 };int lastItem = numbers[^1];int[] middleItems = numbers[1..^1];int[] firstThree = numbers[..3];Console.WriteLine($"Last: {lastItem}, Middle count: {middleItems.Length}");
Breakdown
1
numbers[^1]
The ^1 index refers to the last element of the array.
2
numbers[1..^1]
Extracts elements from index 1 up to (but not including) the last element.
3
numbers[..3]
Shorthand for taking all elements from the start up to index 3.