Search code examples
c#arraysrange

C# range operator, why does this not throw an exception? (int x = someIntArray[2..2])


int[] array = { 10, 20, 30, 40, 50 };
int[] range = array[2..2]; // gives empty array
int[] range2 = array[2..3]; // gives array with one element - 30

I understand range operators somewhat, like the upper bound is exclusive, so [2..3] is asking for index[2] and [0..3] gives elements [0], [1], [2]. Using [0..3] as an example, it seems like its saying "give me elements [0] through [3-1]".

When you use [2..2], it would seem like it's saying [2] through [2-1], which should throw an exception.

I know I'm missing something, I just can't figure out what.


Solution

  • I believe that viewing .. operator as a kind of filter like how a WHERE clause filters a dataset can help understand the behavior here. When one requests arr[2..2], it basically means "give me all the elements starting from index 2 inclusive up to index 2 exclusive" which cannot be satisfied by any elements. Hence, the result is an empty range.

    Thinking about how ^0 works may also help. A statement like arr[^0] throws an exception because such an index is out of bounds of the array. However, arr[0..^0] does not throw an exception. Although the upper index does not exist, since it's exclusive, it does not cause an exception. Yet, there are still elements that satisfy the filter.