C#

C#

Made by DeepSource

Using negative array indices results in IndexOutOfRangeException CS-W1042

Bug risk
Major
Autofix

Languages like Python allow you to access elements from the last by specifying negative indices. However, this does not work in C# and will result in an IndexOutOfRangeException. In order to access elements from the last, consider prefixing the indices with ^ operator.

Bad Practice

var last = arr[-1];

Recommended

var last = arr[^1];

Reference