Archive

Archive for the ‘foreach’ Category

How var fixes a type hole in C#

August 5, 2009 1 comment

Assuming we have:

public class Base {}
public class Derived : Base {}
public class Unrelated {}

Read more...

Categories: C#, foreach Tags: , ,

Further Muddying the ForEach Waters

February 3, 2009 3 comments

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.

Read more…

Categories: C#, delegates, foreach Tags: , ,

The classic delegate/foreach interaction bug (and a solution)

June 13, 2008 2 comments

Update (2012-10-05): This whole issue has now been fixed in C# 5! The compiler just copies the loop variable for you, if you capture it in a closure. This is actually a breaking change, but a perfectly sensible one. Note that this only affects foreach. The plain for loop is unaffected.

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.

Read more...

Follow

Get every new post delivered to your Inbox.