According to MSDN documentation ArgumentOutOfRangeException is :
The exception that is thrown when the value of an argument is outside
the allowable range of values as defined by the invoked method
Which means, the exception will raise when you tried to access an item from a collection based on its index value but actually that index is not within the range of indices. most of the cases collections follows 0
based indexing so if your specific value is below 0
or it is greater than the number of elements in the collection will lead to this exception while accessing.
When we goes through the given snippet, we can see that you have used chars [i - 1]
in different places, obviously this will cause Exception when value of i
is 0
.
In short we can say that, Let chars
be a collection and you are accessing the items based on index, it is important to check chars.Count > 0
if you are accessing a previous item using i-1
and also the loop limit should be less than chars.Count
.
This may be a generalized answer, but hope that it helps you to understand the reason for this error and how to solve them