I was trying to test this case of resusing the loop variable in foreach in c# as mentioned in following question
Is there a reason for C#'s reuse of the variable in a foreach?
After going through this and this, i tried to reproduce this error with for loop as foreach part has been fixed in c# releases.
But to my surprise, when i tried this code, I got an "Index was outside the bounds of the array." exception from code. Although my array has 4 items and i am trying to access the 3rd index.
public static void Main()
{
var strings = new string[] { "sd2", "dafs3", "dasd5", "fdf6" };
var actions = CreateActions(strings);
actions.ForEach(f => f());
}
private static List<Action> CreateActions(string[] strings)
{
var actions = new List<Action>();
for (int i = 0; i < 4; i++)
{
Console.WriteLine(i);
var fiber = strings[i];
actions.Add(() => Console.WriteLine(strings[i]));
}
return actions;
}
Then I changed my code like this
public static void Main()
{
var strings = new string[] { "sd2", "dafs3", "dasd5", "fdf6" };
var actions = CreateActions(strings);
actions.ForEach(f => f());
}
private static List<Action> CreateActions(string[] strings)
{
var actions = new List<Action>();
for (int i = 0; i < 4; i++)
{
Console.WriteLine(i);
var fiber = strings[i];
actions.Add(() => Console.WriteLine(fiber));
}
return actions;
}
This code is running fine and i got no out of range exception which is strange. Also regarding reusing variable my case was proved.
My first code has this output if run upto index 2 in for loop as for index 3 it throw out of range exception.
0
1
2
fdf6
fdf6
fdf6
My second code piece gave this output and list all 4 items in output
0
1
2
3
sd2
dafs3
dasd5
fdf6
Is there any explanation with c# or any issue with my test code.