Wednesday, October 22, 2008

c# foreach considered harmful in V3

If your using C# 3, don't use the foreach keyword as you can replace it with ForEach on List and extention methods:

public static void ForEach(this IEnumerable items, Action action)
{
if (items == null)
return;

if (action == null)
throw new ArgumentNullException("action");

foreach (var item in items)
action(item);
}

This will give you compile time type checking which the foreach keyword would not pick up until runtime.

No comments: