Code Inspection: Index from end must be greater than zero
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: 11 January 2023