You would think that I would learn: Anonymous delegate variable capturing gotcha

time to read 1 min | 141 words

Can you think of anything wrong with this code:

foreach (DataSource value in EtlConfigurationContext.Current.Sources.Values)
{
	ExecutionPackage.Current.RegisterForExecution(
		delegate { value.Start(this); }
		);
}

I stared that this thing for a while before it hit me. Anonymous delegates lexical capture rules inside a loop means that it will take the loop variable, which has the gotcha of keeping the last value of the variable. This keep tripping me, and I really wish the spec would have made an exception for a loop, because this really is a gotcha and not something that I really need to be concerned with.

In keeping with "code should be self documenting" the bug fix looks like this:

foreach (DataSource value in EtlConfigurationContext.Current.Sources.Values)
{
	DataSource cSharpSpec_21_5_2_Damn_It = value; 
	ExecutionPackage.Current.RegisterForExecution(
		delegate { cSharpSpec_21_5_2_Damn_It.Start(this); }
		);
}