I have this list :
IList<Modulo> moduli = (from Modulo module in Moduli
select module).ToList();
and I cycle it with for (notice i=i+2) :
for(int i=0; i<moduli.Count; i=i+2)
{
}
now, I have to check if moduli[i+1] exist (so, the next element), else I'll get a System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
.
How can I check it? Tried with :
if(moduli[i+1] != null)
{
}
but it doesnt works!
Another way of checking if an array is out of bounds is to make a function. This will check if the index is "in bounds". If the index is below zero or over the array length you will get the result false.
You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.
Exception IndexError Raised when a sequence subscript is out of range.
IndexOf() Function in C# The C# Array. IndexOf(array, element) function gets the index of the element element inside the array array . It returns -1 if the element is not present in the array.
Check it the same way as you check your loop condition:
if(i + 1 < moduli.Count) // it exists
Note the <
instead of <=
, which is a mistake in your original code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With