Introduction
In C# you have various possibilities to iterate over a list like for loop, foreach loop or with LINQ. When you use a List(T) type you have even one more, the ForEach method. But this method doesn't show always the same behaviour than a normal foreach loop.
Using the code
The ForEach method of the (not List<T>IList<T>) executes an operation for every object which is stored in the list. Normally it contains code to either read or modify every object which is in the list or to do something with list itself for every object.
Modify the object itself
The following sample with a ForEach method iterates over all stored numbers in the collection. It substracts 10 from every number. At the end the numbers will be printed to the console. Wether it works depends on which data type you use!
List<int>
items = new List<int>() { 14, 19 };
items.ForEach(item
=> item = item - 10);
foreach (int item in items)
{
Console.WriteLine(item);
}
The output in the console is in this case 14 and 19. If the type is a primitive data type (a struct in .NET), the ForEach method doesn't have the effect you want. I didn't expect this result, but after a look at the ForEach definition it becomes clearer. It can't work by design!
//Definition of List<T>.ForEach
public void ForEach(Action<T> action)
//Definition of Action<T>
public delegate void Action<in T>(T obj)
Int is a value type which means, that it is passed to a method by value. By value means the a copy of the object is passed to the method, not the object itself. So if the action, which is passed into the ForEach method, changes the copy, but it won't affect the original object. So in our sample, the original int value won't be changed. The Action delegate also doesn't have a return type, which could be used to update the object in the list.
Join the conversation! Your thoughts help the community grow.