'Accessing a property/field on record type yields an IndexOutOfRangeException
I am developing .Net 5.0 console application in Visual Studio 2017 Community Edition on Windows 7.
When evaluating this C# code:
int weirdIndex = child.Depth - 1; or similarly int weirdIndex = child._depth - 1; an IndexOutOfRangeException gets thrown.
child is of record type Step, which has a private field _depth as well as a public getter Depth. Here is an extract of this record:
record Step
{
/* a bunch of logic */
private readonly int _depth;
public int Depth => _depth;
}
I tried to use struct instead of record type, but it didn't fix the problem.
weirdIndex later is used to access an array, but the bounds are perfectly fine. Here is an extract from the function where weirdIndex is used:
foreach (var child in AllFather.Children)
levels[child.Depth - 1][levelPtrs[child.Depth - 1]] = child.Sum.ToString();
int weirdIndex = child._depth - 1;
Console.WriteLine("Just separating the lines");
levelPtrs[weirdIndex] = levelPtrs[weirdIndex] + 1;
}
Here is a screenshot of the situation:

I want to point out that the message Just separating the lines actually appears in the Console twice before the Exception is thrown.
I tried evaluating the following expressions in the Watch 1 of the Debug Window, and everything had expected values:
Expression | Value
----------------------------------
levelPtrs[0] | 2
child.Depth - 1 | 0
levelPtrs[child.Depth - 1] | 2
I quickly read IndexOutOfRangeException Class reference by Microsoft, and then also found this thread on StackOverflow: What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?, but neithere of them seem to adress the issue I'm having, as far as my understanding goes.
I am very confused and would really appreciate some help. What am I missing? Is this some kind of bug by any chance?
EDIT: levels is of type string[][], levelPtrs is of type int[], and AllFather.Children is of type Step[].
EDIT: I put all the code in public GitLab repo under the branch "indexoutofrangeexception" in case somebody would like to see the whole codebase. It's not big, but quite noisy. Here is the repo: https://gitlab.com/wizardsanimals/funny-problems .
Solution 1:[1]
As @jalepi pointed out in the comments, levels[0] indeed is an array that has not index 2, as it only has a length of 2. That's the reason the exception was thrown.
On line 39 though, not 41. I don't know why Visual Studio decided that the line "int weirdIndex = ..." was the issue, I think it shouldn't have done so. Perhaps it was trying to help.
Thanks everybody for your comments. Moral of the story: check code both below and ABOVE when the cause of exception is unclear.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fyodor Volik |
