Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Any benefit of List<T>.ForEach(...) over plain foreach loop?

Tags:

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();} 

?

like image 895
Cristian Diaconescu Avatar asked Dec 17 '09 20:12

Cristian Diaconescu


1 Answers

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(); } 
like image 80
Justin Long Avatar answered Oct 24 '22 06:10

Justin Long