I have some code and when that executes, that throws a IndexOutOfRangeException, saying,

Index was outside the bounds of the array.

You are watching: System indexoutofrangeexception index was outside the bounds of the array

What go this mean, and also what can I do around it?

Depending ~ above classes provided it can additionally be ArgumentOutOfRangeException

An exception of type "System.ArgumentOutOfRangeException" arisen in mscorlib.dll yet was not taken on in user code additional information: table of contents was the end of range. Must be non-negative and less than the size of the collection.



What Is It?

This exception way that you"re make the efforts to access a arsenal item by index, making use of an invalid index. An index is invalid as soon as it"s lower than the collection"s lower bound or better than or same to the number of elements the contains.

When it Is Thrown

Given range declared as:

byte<> selection = brand-new byte<4>;You can accessibility this selection from 0 to 3, values external this selection will cause IndexOutOfRangeException to be thrown. Mental this once you produce and accessibility an array.

Array LengthIn C#, usually, arrays room 0-based. It method that an initial element has index 0 and also last facet has index size - 1 (where size is total number of items in the array) therefore this password doesn"t work:

array = 0;Moreover please note that if you have a multidimensional variety then friend can"t usage Array.Length for both dimension, you have to use Array.GetLength():

int<,> data = new int<10, 5>;for (int i=0; ns Upper bound Is no InclusiveIn the following example we produce a life bidimensional selection of Color. Every item represents a pixel, indices room from (0, 0) to (imageWidth - 1, imageHeight - 1).

Color<,> pixels = brand-new Color;for (int x = 0; x This code will then fail because variety is 0-based and also last (bottom-right) pixel in the image is pixels:

pixels = Color.Black;In another scenario you may obtain ArgumentOutOfRangeException for this password (for example if you"re using GetPixel method on a Bitmap class).

Arrays do Not GrowAn range is fast. Very fast in straight search contrasted to every other collection. The is due to the fact that items are contiguous in storage so memory resolve can it is in calculated (and increment is just an addition). No have to follow a node list, an easy math! You pay this with a limitation: they can"t grow, if you need an ext elements you should reallocate that selection (this may take a fairly long time if old items need to be replicated to a brand-new block). You resize them through Array.Resize(), this instance adds a brand-new entry to an present array:

Array.Resize(ref array, array.Length + 1);Don"t forget that valid indices space from 0 to size - 1. If you simply try to assign things at size you"ll obtain IndexOutOfRangeException (this actions may confused you if girlfriend think lock may rise with a syntax comparable to Insert technique of other collections).

Special Arrays with Custom lower BoundFirst article in arrays has constantly index 0. This is not always true because you deserve to create an array with a custom reduced bound:

var variety = Array.CreateInstance(typeof(byte), new int<> 4 , brand-new int<> 1 );In the example, array indices space valid from 1 to 4. Of course, upper bound cannot be changed.

Wrong ArgumentsIf you accessibility an array using unvalidated disagreements (from user entry or from role user) you may gain this error:

private static string<> RomanNumbers = brand-new string<> "I", "II", "III", "IV", "V" ;public revolution string Romanize(int number) return RomanNumbers;Unexpected ResultsThis exception may be thrown for another reason too: by convention, numerous search functions will return -1 (nullables has actually been presented with .NET 2.0 and anyway it"s likewise a famous convention in use from numerous years) if castle didn"t uncover anything. Let"s imagine girlfriend have selection of objects similar with a string. You may think to compose this code:

// Items similar with a stringConsole.WriteLine("First item equals to "Debug" is "0".", myArray);// arbitrary objectsConsole.WriteLine("First item amounts to to "Debug" is "0".", myArray x.Type == "Debug")>);This will fail if no items in myArray will fulfill search condition due to the fact that Array.IndexOf() will certainly return -1 and then array accessibility will throw.

Next example is a naive instance to calculate occurrences of a given set of numbers (knowing preferably number and also returning range where item at index 0 represents number 0, item at index 1 represents number 1 and also so on):

static int<> CountOccurences(int maximum, IEnumerable numbers) int<> an outcome = brand-new int; // has 0 foreach (int number in numbers) ++result; return result;Of course, it"s a pretty disastrous implementation but what I want to show is the it"ll failure for an unfavorable numbers and numbers above maximum.

How it applies to List?

Same instances as array - selection of precious indexes - 0 (List"s indexes always start through 0) come list.Count - accessing elements outside the this range will cause the exception.

Note that List throws ArgumentOutOfRangeException because that the same instances where arrays usage IndexOutOfRangeException.

Unlike arrays, perform starts empty - for this reason trying to access items of just developed list lead to this exception.

var list = new List();Common instance is come populate list with indexing (similar come Dictionary) will cause exception:

list<0> = 42; // exceptionlist.Add(42); // correctIDataReader and ColumnsImagine you"re trying to read data indigenous a database through this code:

using (var connection = CreateConnection()) utilizing (var command = connection.CreateCommand()) command.CommandText = "SELECT MyColumn1, MyColumn2 native MyTable"; using (var reader = command.ExecuteReader()) if (reader.Read()) ProcessData(reader.GetString(2)); // Throws! GetString() will certainly throw IndexOutOfRangeException since you"re dataset has actually only two columns however you"re do the efforts to obtain a worth from 3rd one (indices space always 0-based).

Please keep in mind that this actions is shared with most IDataReader implementations (SqlDataReader, OleDbDataReader and also so on).

You can acquire the very same exception also if you usage the IDataReader overload that the indexer operator the takes a pillar name and also pass an invalid shaft name.Suppose for example that you have actually retrieved a column called Column1 but then you try to retrieve the value of that field with

var data = dr<"Colum1">; // absent the n in Column1.This happens because the indexer operator is imposed trying come retrieve the table of contents of a Colum1 field that doesn"t exist. The GetOrdinal technique will litter this exception when its interior helper password returns a -1 as the table of contents of "Colum1".

OthersThere is one more (documented) case when this exception is thrown: if, in DataView, data tower name being offered to the DataViewSort home is no valid.

How come Avoid

In this example, allow me assume, for simplicity, that arrays are always monodimensional and 0-based. If you desire to be strictly (or you"re arising a library), you might need to replace 0 v GetLowerBound(0) and also .Length with GetUpperBound(0) (of course if you have parameters of form System.Array, the doesn"t use for T<>). Please keep in mind that in this case, upper bound is inclusive climate this code:

for (int i=0; i have to be rewritten choose this:

for (int i=array.GetLowerBound(0); ns Please note that this is not enabled (it"ll throw InvalidCastException), that"s why if her parameters are T<> you"re safe around custom reduced bound arrays:

void foo(T<> array) void test() // This will throw InvalidCastException, cannot transform Int32<> come Int32<*> foo((int)Array.CreateInstance(typeof(int), brand-new int<> 1 , new int<> 1 ));Validate ParametersIf index comes from a parameter girlfriend should always validate lock (throwing proper ArgumentException or ArgumentOutOfRangeException). In the following example, not correct parameters may reason IndexOutOfRangeException, users of this duty may suppose this because they"re passing variety but it"s not always so obvious. I"d indicate to constantly validate parameters because that public functions:

static void SetRange(T<> array, int from, int length, Func function){ if (from = array.Length) throw new ArgumentOutOfRangeException("from"); if (length array.Length) throw new ArgumentException("..."); because that (int i=from; i If role is exclusive you may simply replace if logic through Debug.Assert():

Debug.Assert(from >= 0 && indigenous Check thing StateArray index might not come straight from a parameter. It may be part of thing state. In general is constantly a good practice come validate thing state (by itself and with role parameters, if needed). You deserve to use Debug.Assert(), throw a appropriate exception (more descriptive about the problem) or handle that choose in this example:

class Table { public int SelectedIndex get; set; windy Row<> Rows get; set; public row SelectedRow get if (Rows == null) throw new InvalidOperationException("..."); // No or dorn selection, below we just return null because that // this case (it might be the reason we use this residential or commercial property // rather of direct access) if (SelectedIndex = Rows.Length) return null; return Rows; Validate Return ValuesIn among previous instances we straight used Array.IndexOf() return value. If we know it may fail climate it"s better to manage that case:

int table of contents = myArrayHow to DebugIn mine opinion, many of the questions, here on SO, around this error have the right to be simply avoided. The moment you spend to compose a appropriate question (with a little working example and a little explanation) can easily much an ext than the moment you"ll should debug her code. Very first of all, read this Eric Lippert"s blog post around debugging of tiny programs, ns won"t repeat his native here but it"s absolutely a must read.

You have source code, friend have exception message with a stack trace. Go there, pick best line number and also you"ll see:

array = newValue;You discovered your error, inspect how table of contents increases. Is the right? examine how variety is allocated, is meaningful with how index increases? Is it appropriate according to your specifications? If you answer yes to every these questions, then you"ll find good help here on digitalrecordersreview.org however please very first check for the by yourself. You"ll save your own time!

A great start allude is to constantly use assertions and also to validate inputs. Girlfriend may even want to usage code contracts. Once something go wrong and also you can"t number out what happens with a quick look at your password then you have to resort to an old friend: debugger. Simply run your application in debug within Visual Studio (or your favorite IDE), you"ll see specifically which line throws this exception, which variety is involved and also which index you"re trying come use. Really, 99% that the times you"ll deal with it by yourself in a few minutes.

If this happens in production then you"d far better to include assertions in incriminated code, most likely we won"t view in your password what girlfriend can"t check out by yourself (but you can always bet).

The VB.NET next of the story

Everything the we have said in the C# price is valid for VB.NET with the evident syntax differences but there is critical point to think about when you attend to VB.NET arrays.

See more: Watch That Time I Got Reincarnated As A Slime Episode 26 Online

In VB.NET, arrays room declared setting the maximum valid index worth for the array. That is not the counting of the aspects that we want to store in the array.

" declares variety with an are for 5 essence " 4 is the maximum valid index beginning from 0 to 4Dim myArray(4) together IntegerSo this loop will fill the range with 5 integers there is no causing any IndexOutOfRangeException

For i together Integer = 0 to 4 myArray(i) = iNext

The VB.NET rule

This exception means that you"re make the efforts to access a arsenal item by index, using an invalid index. An index is invalid as soon as it"s reduced than the collection"s lower bound or better than same to the variety of elements it contains. The maximum allowed index defined in the variety declaration