"System.ArgumentOutOfRangeException" why is it showing? And why does the list<>number stop printing?

Viewed 107

When I execute it, it stops printing at 8 and shows me

"System.ArgumentOutOfRangeException"

List<int> number = new List<int> { 1, 2, 2, 5, 4, 8, 6};
number.ForEach(delegate (int i) { Console.WriteLine(number[i]); });
Console.ReadKey();
2 Answers

As @tkausl already mentioned, ForEach passes you the value, not the index, it is not recommended to use List.ForEach actually, but if you still want to use it, you can do something like this:

 number.ForEach(c => { Console.WriteLine(c); });

You can simply use a foreach like this:

foreach (var c in number)
{
   Console.WriteLine(c);
}

You can find the discussion here: foreach vs someList.ForEach(){}

You can use this foreach , It will never make a mistake

List<int> number = new List<int> { 1, 2, 2, 5, 4, 8, 6 };
foreach (var item in number)
{
    Console.WriteLine(item);
}
Related