Index was outside the bounds of the array in c# : IndexOutOfRange
Asked
Active
Viewed 80 times
-2
-
How do you know that `filesIndex` was not outside the bounds of the array? There's nothing in your code that would ensure that structurally. Add a check before you use the variable and see if it fires. – Tumbleweed53 Dec 03 '20 at 15:26
-
@HereticMonkey No. – May M Dec 03 '20 at 15:38
-
@Tumbleweed53 Yes it triggers the fire then we see the issue as mentioned. – May M Dec 03 '20 at 15:43
1 Answers
0
Well you initialize your array fileData = new string[2]
with a size of 2. For the 3rd file that matches your condition, fileIndex will be 2 and thus outside the array's bounds.
As you don't know how may files will match on beforehand, use a List<string>
instead.

CodeCaster
- 147,647
- 23
- 218
- 272
-
but the issue is in this line int filesIndex = 0; within the IF loop when i replace 0 with filesIndex that is causing the error. Can you share me the block with the code updated? – May M Dec 03 '20 at 15:39
-
No, the exception occurs at `fileData[filesIndex]`. Make fileData a `List
` instead, and `.Add()` to it. – CodeCaster Dec 03 '20 at 15:45 -
-