Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index was outside the bounds of array when using List<Func<T,object>>

Tags:

c#

func

I have a class like this:

class MyClass { public object[] Values; }

Somewhere else I'm using it:

MyClass myInstance = new MyClass() {Values = new object[]{"S", 5, true}};

List<Func<MyClass, object>> maps = new List<Func<MyClass, object>>();

for (int i = 0; i < myInstance.Values.Length ; i++)
{
    maps.Add(obj => obj.Values[i]);
}

var result = maps[0](myInstance); //Exception: Index outside the bounds of the array

I thought it will returns S, but it throw exception. Any idea what is going on?

like image 782
Hossein Narimani Rad Avatar asked Dec 23 '13 08:12

Hossein Narimani Rad


People also ask

How do you solve an index outside the bounds of the array?

U are accessing an empty array with some index greater than zero, it returns this error. Solution : Check the array count before you access it through index !

What does it mean when the index is outside the bounds of the array?

The ArrayIndexOutOfBoundsException is one of the most common errors in Java. It occurs when a program attempts to access an invalid index in an array i.e. an index that is less than 0, or equal to or greater than the length of the array.

How do I fix IndexOutOfRangeException?

Solutions to Prevent IndexOutOfRangeException Solution 1: Get the total number of elements in a collection and then check the upper bound of a collection is one less than its number of elements. Solution 2: Use the try catch blocks to catche the IndexOutOfRangeException .

What is index out of range exception in C#?

IndexOutOfRangeException occurs when you try to access an element with an index that is outsise the bounds of the array.


1 Answers

To see what's going on, change your lambda to maps.Add(obj => i);.

With that change result will be 3, and that's why you're getting IndexOutOfBoundException exception: you're trying to get myInstance[3] which does not exist.

To make it work, add local int variable within your loop and use that one as index instead of loop counter i:

for (int i = 0; i < myInstance.Values.Length; i++)
{
    int j = i;
    maps.Add(obj => obj.Values[j]);
}
like image 105
MarcinJuraszek Avatar answered Sep 28 '22 18:09

MarcinJuraszek