Mastering C# array slicing - A guide to the .. (range) and ^ (hat) operators
From time to time, I like to refresh my knowledge of some basic features of C#. Today, we are going to focus on the ..
operator, also known as the range operator, and the ^
operator, also known as the hat operator.
How the .. operator works
Using the range operator, we can extract elements from an array more efficiently than conventional approaches. Let’s consider the following example with an array of integers.
int[] array = { 1, 5, 12, 4, 22, 10 };
int[] subArray1= array[..2];
int[] subArray2 = array[3..];
// It will print: 1 5
Console.WriteLine(string.Join(" ", subArray1));
// It will print: 4 22 10
Console.WriteLine(string.Join(" ", subArray2));
- Remember, the number in the
..
operator always starts from the 0 (zero) index. - The
..2
expression is inclusive of the first element and exclusive of the element at the specified index. So in our example, it starts from the element at index 0 and ends before the element at index 2. - The
3..
expression is inclusive of the element at the specified index and goes until the last element of the array. So in our example, it starts from the element at index 3 and includes all subsequent elements.
How the ^ operator works
The ^
operator selects an element from the end of an array based on the number specified in the expression. Consider the following example:
int[] array = { 1, 5, 12, 4, 22, 10 };
int secondNumberFromTheEnd = arr[^2];
// It will print: 22
Console.WriteLine(secondNumberFromTheEnd);
How to combine the .. and ^ operators
We can combine the two operators to extract parts of an array, this time using elements from the end of the array. Consider the following example:
int[] array = { 1, 5, 12, 4, 22, 10 };
int[] subArray3 = array[..^2];
int[] subArray4 = array[^3..];
// It will print: 1 5 12 4
Console.WriteLine(string.Join(" ", subArray3));
// It will print: 4 22 10
Console.WriteLine(string.Join(" ", subArray4));
-
The
..^2
expression in inclusive from the first element of the array and exclusive of the element at the specified index from the end. The equivalent using the..
operator would be..4
. -
The
^3..
expression is inclusive of the third element from the end of the array and goes until the last element. The equivalent using the..
operator would be3..
.
Conclusion
The ..
and ^
operators can be very helpful when working with arrays and wanting to slice from their elements. In my examples, I used integers, but you can experiment with arrays of other primitive types or objects.