4

I haven't used anonymous methods. I found a code where a list is being iterated as shown in code snippet 1. Why would the code snippet 1 be preferred over 2?

    List<String> names = new List<String>(); 

    ... 
    //Code snippet 1
    names.ForEach(delegate(String name)
    {
        Console.WriteLine(name);
    });

    //Code snippet 2
    foreach (string name in names)
    {
        Console.WriteLine(name);
    }
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
softwarematter
  • 28,015
  • 64
  • 169
  • 263
  • 4
    I have not known that snippet 1 is preferred over 2. Any proof? – Delta76 May 18 '11 at 09:29
  • I was also wondering why would anyone go for snippet 1. In fact, I found this in the code base of the project I am working on that someone else coded. – softwarematter May 18 '11 at 09:30
  • I would strongly prefer the second over the first. I'd only use something like the first if I need it. For example in parallel for. – CodesInChaos May 18 '11 at 09:37

2 Answers2

7

I don't see snippet 1 used much at all. I do see a variation of it using lambda expressions.

names.ForEach(x=> Console.WriteLine(x));
SquidScareMe
  • 3,108
  • 2
  • 24
  • 37
0

In this case, there is no benefit.

You would find older programmers using method 2 in your example and newer programmers might use method 1.

Older programmers have more experience prior to anonymous methods, anonymous methods are new and not "ingrained in their soul" and they automatically program in style #2.

New programmers might use #1 because they keep thinking everything is a method call.

Bill
  • 187
  • 1
  • 2
  • Consider reading [this article](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx) comparing the two approaches. – Servy May 03 '13 at 17:15