<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Why Can&#039;t You Code? &#187; .net 4</title>
	<atom:link href="http://www.whycantyoucode.com/tag/net-4/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.whycantyoucode.com</link>
	<description>The highest form of ignorance is when you reject something you don&#039;t know anything about.</description>
	<lastBuildDate>Thu, 25 Feb 2010 14:39:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Beware of the Lazy&lt;T&gt; .NET 4.0 type. The closure trap.</title>
		<link>http://www.whycantyoucode.com/2009/11/beware-of-the-lazyt-net-4-0-type-the-closure-trap/</link>
		<comments>http://www.whycantyoucode.com/2009/11/beware-of-the-lazyt-net-4-0-type-the-closure-trap/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 13:42:00 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[.NET 4.0]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[.net 4]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[lazy]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/?p=69</guid>
		<description><![CDATA[The System.Lazy&#60;T&#62; type in the new .NET 4.0 framework came to my attention recently. This type is not at all revolutionary. In fact, everyone could have written it themselves in under 10 lines of code going as far back as the .NET 2.0 framework. Some less experienced programmers won’t realize however, that deferring the call [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/dd642331%28VS.100%29.aspx">System.Lazy&lt;T&gt;</a> type in the new .NET 4.0 framework <a href="http://weblogs.asp.net/fredriknormen/archive/2009/11/10/net-4-0-is-to-lazy.aspx">came to my attention</a> recently. This type is not at all revolutionary. In fact, everyone could have written it themselves in under 10 lines of code going as far back as the .NET 2.0 framework.</p>
<p>Some less experienced programmers won’t realize however, that deferring the call to a delegate could have nasty side effects.</p>
<p>Consider the following code snippet:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    List&lt;Lazy&lt;string&gt;&gt; lazyInit = new List&lt;Lazy&lt;string&gt;&gt;();
    for (char letter = 'A'; letter &lt;= 'Z'; letter++)
    {
        var lazy = new Lazy&lt;string&gt;(() =&gt; letter.ToString());
        lazyInit.Add(lazy);
    }
    foreach (var lazy in lazyInit)
    {
        Console.Write(lazy.Value);
    }
    Console.ReadLine();
}</pre>
<p>The code is pretty straight forward, but what gets printed here? Would you think it’s the alphabet? You would be very wrong.</p>
<p><a href="http://www.whycantyoucode.com/content/uploads/2009/11/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.whycantyoucode.com/content/uploads/2009/11/image_thumb1.png" width="678" height="375" /></a></p>
<p>The output is exactly<strong> ‘ZZZZZZZZZZZZZZZZZZZZZZZZZ’</strong>. Go ahead, run it yourself if you don’t trust me.</p>
<p>To understand why this happens, you need to understand how closures work.</p>
<p>In the constructor to the Lazy&lt;&gt; class, you’re passing in a delegate, in the form of a lambda. This delegate captures the <strong>letter</strong> variable (attention, <span style="text-decoration: underline">not its value at the time of the call, but the variable as a whole</span>) and creates a<strong> closure</strong> class around it behind the scenes. This may be counter-intuitive to the average programmer.&#160; For further information on what happens behind the scenes with captured variables and closures, <a href="http://marcgravell.blogspot.com/2009/08/using-reflector-to-understand-anonymous.html">read this great post by Marc Gravell</a>.</p>
<p>This is not specific behavior of the new Lazy&lt;T&gt; class, it’s what happens every time a delegate is stored for <strong>deferred</strong> execution.</p>
<p>If you rewrite the code without deferred execution, you’ll see that the problem doesn’t manifest itself:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    for (char letter = 'A'; letter &lt;= 'Z'; letter++)
    {
        var lazy = new Lazy&lt;string&gt;(() =&gt; letter.ToString());
        Console.Write(lazy.Value);
    }
    Console.ReadLine();
}
// Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ</pre>
<p>Same delegate is being used, but it is executed <strong>immediately</strong>. The output is now the complete English alphabet, as you would expect.</p>
<p>This isn’t very useful however, We’ve completely thrown away the advantages of the Lazy&lt;T&gt; class and we might as well not be using it.</p>
<p>So, how can we fix it? We need to use an intermediary variable inside the body of the<strong> for</strong> loop that is simply a copy of the outer variable. The inner variable’s scope is unique to each loop iteration, so it matters a whole lot where you define your variables.</p>
<p>Fixed code:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
    List&lt;Lazy&lt;string&gt;&gt; lazyInit = new List&lt;Lazy&lt;string&gt;&gt;();

    // char letter2; // &lt;- for the sake of exercise, uncomment this line and remove the ‘char’ keyword from the initialization of the letter2 variable inside the for loop below. the ‘bug’ will manifest itself again
    for (char letter = 'A'; letter &lt;= 'Z'; letter++)
    {
        char letter2 = letter; // value re-captured in inner block (remove ‘char’ keyword and uncomment line above to see the ‘bug’ manifest itself again)
        var lazy = new Lazy&lt;string&gt;(() =&gt; letter2.ToString());
        lazyInit.Add(lazy);
    }
    foreach (var lazy in lazyInit)
    {
        Console.Write(lazy.Value);
    }
    Console.ReadLine();
}</pre>
<p>One tool that can automatically check for this condition so you can avoid headaches later is <a href="http://www.jetbrains.com/resharper/">JetBrain’s Resharper</a>. With <em>Resharper</em> installed, you’d see a warning underneath () =&gt; <span style="text-decoration: underline">letter.ToString()</span> which spells <strong>‘Access to modified closure’</strong> and suggests the same fix I described in this blog post.</p>
<p>If anyone’s interested in seeing how the same Lazy&lt;T&gt; class could be implemented in .NET 2.0 and up, leave a comment and I’ll post it here!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2009/11/beware-of-the-lazyt-net-4-0-type-the-closure-trap/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

