Sunday, October 12, 2008

Little deception of List.ForEach(Action action)

I use foreach statement really often. It is useful and more compact than for. (This way is fast in same case but in same case it is slowly for performance. But I want say not about that). List<T> class has ForEach(Action action) method I thought that its implementation (and behaviour) is like foreach statement (I make this conclusion, based on the name of method) but I was confused. I have looked to Net. Reflector and saw next code:

public static void ForEach(T[] array, Action action)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (action == null)
{
throw new ArgumentNullException("action");
}
for (int i = 0; i < array.Length; i++)
{
action(array[i]);
}
}

ForEach(Action action) method behaviour likes for statement behaviour. And I can use it like for. For example I can change main collection during execution action delegate.

No comments: