Search code examples
c#.netanonymous-methods

Use of anonymous method


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

Solution

  • 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));