What is an IndexOutOfRangeException or ArgumentOutOfRangeException and how do I fix it?
What is an IndexOutOfRangeException or ArgumentOutOfRangeException and how do I fix it?
This exception means that you're trying to access a
collection item by index, using an invalid index. An index is invalid when it's
lower than the collection's lower bound or greater than or equal to the number
of elements it contains.
When It Is Thrown
Given an array declared as:
byte[] array = new byte[4];
You can access this array from 0 to 3, values outside this
range will cause IndexOutOfRangeException to be thrown. Remember this when you
create and access an array.
Array Length
In C#, usually, arrays are 0-based. It means that first
element has index 0 and last element has index Length - 1 (where Length is
total number of items in the array) so this code doesn't work:
array[array.Length] = 0;
Arrays Do Not Grow
An array is fast. Very fast in linear search compared to
every other collection. It is because items are contiguous in memory so memory
address can be calculated (and increment is just an addition). No need to
follow a node list,
simple math! You pay this with a limitation: they can't
grow, if you need more elements you need to reallocate that array (this may
take a relatively long time if old items must be copied to a new block). You
resize them with Array.Resize<T>(), this example adds a new entry to an existing
array:
Array.Resize(ref array, array.Length + 1);
Comments
Post a Comment