ReSharper 2024.3 Help

Code inspection: Index from end must be greater than zero; use '^1' to refer to the last element

The reverse index operator ^ introduced in C# 8.0 might lead to a mistake of referring to the last element with ^0, the same way as you refer to the first element 0. However, the index from end is designed to start with 1, and therefore using ^0 as an index will result in an IndexOutOfRangeException in runtime.

This StackOverflow answer provides a good explanation of why index from end stars with 1 and not with 0.

To fix this problem, replace ^0 with ^1 in the index.

void Sample() { var numbers = new[] { "one", "two", "three" }; var three = numbers[^0]; Console.WriteLine(three); }
void Sample() { var numbers = new[] { "one", "two", "three" }; var three = numbers[^1]; Console.WriteLine(three); }
Last modified: 08 April 2024