How var fixes a type hole in C#
Assuming we have:
public class Base {}
public class Derived : Base {}
public class Unrelated {}
Assuming we have:
public class Base {}
public class Derived : Base {}
public class Unrelated {}
ForEach is regularly proposed as a missing feature in the BCL but has been rejected in the past apparently because it wouldn’t be "functional" enough, doesn’t return anything so calls cannot be chained together in a LINQ-like pipeline, and so on. So here’s a different approach that is undeniably functional, and does support chaining together.
Update (2011-06-17): Since I posted this I’ve regularly been told that there’s another solution where you declare a local variable inside the loop and copy the loop variable into it. Thanks, but I know that already! That’s the first solution everyone learns. The idea here was to suggest an alternative solution that works more elegantly, without adding extra clutter.
If you’ve used C# anonymous delegates or lambdas for a while (or anonymous functions in JavaScript) you will have encountered this problem. You make a delegate for each item in a list, and they all seem to wind up referring to the last item on the list. FUME!
It’s just an unfortunate side effect of the way foreach works. It reuses the same loop variable each time around the loop, and so that loop variable is created outside the scope of the loop, and so all the delegates you create inside the loop are actually looking at the same variable, not their own local copies.