C#: Warn about negative index when accessing arrays

I have just ran into a bug in our application due to the following code which resulted from a wrong assumption on how C# indexes work

MyObject[] requestsInMonth = /* some code here */;
var last = requestsInMonth[^-1]; // This breaks, I actually meant requestsInMonth[^1]

In general, I am not sure whether known negative values when indexing C# arrays (and Lists, and at least some other known collections) make any sense in any context.
Therefore, I think it would make sense to mark this case as a Major (or even Critical) Bug.

All of these cases would be flagged:

  • someArray[-1]
  • someArray[^-1]
  • someArray[0..^-1]


Are you on SonarCloud or SonarQube? And if the latter, which version?


SonarQube: Version 10.1 (build 73491)
SonarLint: 6.10.69538 on Visual Studio 2022 (NOT connected mode)

1 Like

Hey @m-gallesio , very good catch!

I am honestly surprised this is valid from the compiler’s perspective, since it is a guaranteed runtime exception. :slight_smile:

I made an issue in the C# analyzer repository. Click here
I also added some extra cases that are always runtime exceptions, such as 0 and >Length.
I also linked this thread to the issue.
Feel free to add any comments you might have there.


1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.