Innexoutofrangexception in the c#
IndexoutoFRANGEEXCEPTION occurs when trying to access the array or set the element of the effective index range in the collection. This means that the index you use is lower than the upper boundary of the lower bound or higher than (or equal) collection. The timing of abnormal occurrence
Consider a array called
, size 4:
access index 0 to 3 is valid, but trying to access will trigger indexoutofrangexception abnormalities. array
<code class="language-csharp">byte[] array = new byte[4];</code>
array[4]
<.> 1. The length of the array
The array is based on 0, so the index of the first element is 0, and the index of the last element is length -1.
Avoid using index access elements equal to Length, such as .
array[array.Length] = 0;
Array index does not include the upper bounds. access.
<.> 3. The array will not automatically growpixels[imageWidth, imageHeight]
<.> 4. Customized array boundary
Array.Resize<T>()
Verify parameters entering or passed to the function to prevent access to indexes beyond the range.
The search function may return -1 to the unusual items. Treatment of these situations to avoid abnormalities in subsequent array access.
When accessing data from the database with IDAREADER, make sure to provide effective column indexes.
How to avoid
Use or object state verification to ensure the correct prerequisite.
Check the stack tracking to determine the line of abnormalities. Check the relevant array and indexes to ensure that they are within the effective range.
The above is the detailed content of Why Does an IndexOutOfRangeException Occur in C#?. For more information, please follow other related articles on the PHP Chinese website!