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

1

6

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?

Incurve answered 23/12, 2013 at 8:6 Comment(0)
B
8

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]);
}
Bawdry answered 23/12, 2013 at 8:11 Comment(2)
Yes, it solved the problem. but can you explain why the i value is acting like reference values?Incurve
@BolucPapuccuoglu +1 yes that's right. I didn't know its name.Incurve

© 2022 - 2024 — McMap. All rights reserved.