In -depth understanding of
and IndexOutOfRangeException
ArgumentOutOfRangeException
and
are common abnormalities in C#. They are thrown when they use invalid indexes or parameters when accessing array, list or collection.
IndexOutOfRangeException
The timing of abnormal occurrence ArgumentOutOfRangeException
Arrays: The access to the number of the number of the number exceeds the upper or lower limit of the array. The array in C#is based on 0, which means that the index of the first element is 0.
Index attributes: - Use invalid index settings or access attributes. For example, if a class has an index attribute called "Items", accessing items [6] in a class with only 5 projects will cause abnormalities.
List (List
): - The access range exceeds [0, list.count -1].
Data source:
Try to access columns according to the index in the IDAREADER or similar data source, and the column does not exist or is incorrect. -
Common reasons
-
"Cross -Border" errors or calculation errors occur when accessing indexes.
Assume that the upper limit of the array is included.
Use invalid parameters or non -integer indexes.
Lifn the initialization or verification input before trying to access the set.
- How to avoid
-
- Verify all input indexes and parameters before accessing the set.
- Check the array length and list count before accessing the element.
When iterated in the array or list, use clearly specifying the cycle of the boundary.
Consider using a collection class like list , they allow boundary checks during compilation.
Make sure the index attribute has a strong verification function to prevent invalid access. -
- How to debug
-
- Use the debugging tool to set the breakpoint at the position that is abnormal.
Check the stack tracking to identify the problem -related code line. -
Check the input value used to access the set.
Verify whether the collection of the accession is correctly initialized and filled.
Make sure that the custom indexing logic has been correctly implemented and handled the edge conditions.
- The differences between vb.net
-
VB.NET array declaration uses the biggest index instead of counting. Therefore, the effective index of an array with a size N is from 0 to N-1. Try to access indexes greater than or equal to N will cause abnormalities. -
The above is the detailed content of What's the Difference Between IndexOutOfRangeException and ArgumentOutOfRangeException in C#?. For more information, please follow other related articles on the PHP Chinese website!