Reputation: 29168
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);
}
Upvotes: 4
Views: 1544
Reputation: 187
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.
Upvotes: 0
Reputation: 3208
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));
Upvotes: 7