A software engineers guide to the galaxy

Sep 19, 2008

strange c# lambda expression behavior

Here's a nice one:

public static void Foreach<T>(
this IEnumerable<T> collection,
Action<T> action)
{
foreach (var item in collection)
action(item);
}

public static IEnumerable<T> Foreach<T>(
this IEnumerable collection,
Func<Object, T> action)
{
foreach (var item in collection)
yield return action(item);
}

var files = Directory.GetFiles(dir, "*.xml");
// #1
files.Foreach(xmlFile => DoSomething(xmlFile));

// #2
files.Foreach(xmlFile => { DoSomething(xmlFile); });

Given that the files array is not empty.

#1 doesn't call DoSomething(), #2 does. Why?

Labels: ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home