I'm wondering why List<T>.ForEach(Action<T>)
exists.
Is there any benefit/difference in doing :
elements.ForEach(delegate(Element element){ element.DoSomething(); });
over
foreach(Element element in elements) { element.DoSomething();}
?
One key difference is with the .ForEach method you can modify the underlying collection. With the foreach syntax you'll get an exception if you do that. Here's an example of that (not exactly the best looking but it works):
static void Main(string[] args) { try { List<string> stuff = new List<string>(); int newStuff = 0; for (int i = 0; i < 10; i++) stuff.Add("."); Console.WriteLine("Doing ForEach()"); stuff.ForEach(delegate(string s) { Console.Write(s); if (++newStuff < 10) stuff.Add("+"); // This will work fine and you will continue to loop though it. }); Console.WriteLine(); Console.WriteLine("Doing foreach() { }"); newStuff = 0; foreach (string s in stuff) { Console.Write(s); if (++newStuff < 10) stuff.Add("*"); // This will cause an exception. } Console.WriteLine(); } catch { Console.WriteLine(); Console.WriteLine("Error!"); } Console.ReadLine(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With