C# - What is the [x..y] range operator?

Almost 5 years ago I made a post on the null-conditional operator (?:) in C#. Now I am following up with a series on different operators. This post is on the range operator ([x..y]). This operator can also be used in combination with "from end" operator (^).

The range operator is a very intuitive operator, in simple terms it returns a subset of a list from index x to index y ([x..y]). The first parameter (x) in the operator is the starting point and the second (y) is the end point. Keep this in mind as you look at the examples below, all the examples have a list of ten numbers, which we create different subsets (ranges) of:

In the first example we start at zero and take three items. This is a simple use of the operator but quite common:

var list = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var range = list[0..3]; //Start at 0, take 3.
Assert.Equal(new[] { 1, 2, 3 }, range);

Instead of starting at zero you can also start at another index, such as below where we start at three and take up until six. I added this example to state that the operator does not start at x and take y items. It starts at x and ends at y:

var list = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var range = list[3..6]; //Start at 3, take up until 6 (3 to 6)
Assert.Equal(new[] { 4, 5, 6 }, range);

You can combine the range operator with the "from end" operator (^), in the below example we take everything from zero to seven. This is because we skip the last three items by using the from end operator. You can see the "^3" part as list.Length - 3:

var list = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var range = list[0..^3]; //Start at 0, take up until the last 3. (0 to 7)
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6, 7  }, range);

You can also leave the operator open ended as seen below, this way y will be the length of the range and it will return everything after three:

var list = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var range = list[3..]; //Skip first 3, return the rest
Assert.Equal(new[] { 4, 5, 6, 7, 8, 9, 10 }, range);

You can use the "from end" operator on both x and y. Below we use it to start three from the max length of the array and take the rest of the array:

var list = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var range = list[^3..]; //Start 3 from the back, take the rest
Assert.Equal(new[] { 8, 9, 10 }, range);

The range operator is often used to substring strings, below is a string with the numbers one to nine, we then use the range operator to take the first five:

var numbers = "123456789";
var toFive = numbers[0..5];
Assert.Equal("12345", toFive);

You can read more on the range operator here. I hope you found this post helpful, feel free to leave a comment down below :)

More on operators from my blog: