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)); 

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));

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.

comments powered by Disqus