The index was outside the array when using List <Func <T, object >>

I have a class like this:

class MyClass { public object[] Values; } 

Somewhere else I use 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 he would return S , but this is an exception. Any idea what is going on?

+6
source share
1 answer

To find out what is going on, change your lambda to maps.Add(obj => i); .

With this change, the result will be 3 , and why you get an IndexOutOfBoundException : you are trying to get myInstance[3] , which does not exist.

To make it work, add a local int variable to your loop and use it as an index instead of the loop counter i :

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

All Articles