<?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; delegate</title>
	<atom:link href="http://www.whycantyoucode.com/tag/delegate/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>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Extension method of the day: Inline using() { } block in C#</title>
		<link>http://www.whycantyoucode.com/2009/11/extension-method-of-the-day-inline-using-block-in-c/</link>
		<comments>http://www.whycantyoucode.com/2009/11/extension-method-of-the-day-inline-using-block-in-c/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 11:20:47 +0000</pubDate>
		<dc:creator>Andrei Alecu</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[disposable]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[extension method]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[using]]></category>

		<guid isPermaLink="false">http://www.whycantyoucode.com/?p=113</guid>
		<description><![CDATA[Linq-to-SQL is our ORM of choice until the Entity Framework matures &#8211; and in our projects we use a factory method to get a new reference to our database data context. Here’s what I mean:
var db = Database.GetDataContext();

  The DataContext class implements IDisposable, which means that (usually) it should be wrapped in an using [...]]]></description>
			<content:encoded><![CDATA[<p>Linq-to-SQL is our <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" target="_blank"><acronym title="Object-relational mapping">ORM</acronym></a> of choice until the Entity Framework matures &#8211; and in our projects we use a factory method to get a new reference to our database data context. Here’s what I mean:</p>
<pre class="brush: csharp;">var db = Database.GetDataContext();</pre>
<p>
  <br />The DataContext class implements <code>IDisposable</code>, which means that (usually) it should be wrapped in an <code>using</code> block: </p>
<p></p>
<pre class="brush: csharp;">using (var db = Database.GetDataContext())
{
    ... code that uses the database here ...
}</pre>
<p>We discovered that we frequently have one liners inside the <code>using</code> block, and in most of these cases, we just return some quick value from the database. </p>
<p>This made me think if there was something I could do about this to make it into a more compact construct. The result is an extension method that lets me do all of this on one line, while also taking care of object disposal.</p>
<p><strong>Introducing &lt;IDisposable&gt;.Using() extension method:</strong></p>
<pre class="brush: csharp;">int userCount = Database.GetDataContext().Using(db =&gt; db.Users.Count()); // get a quick user count</pre>
<p>
  <br />Of course, this applies to any object implementing <code>IDisposable</code>, not just Linq-to-SQL – so it has lots of possible uses. Here’s another example: </p>
<p></p>
<pre class="brush: csharp;">

foreach (string file in Directory.GetFiles(@&quot;C:\TextFiles&quot;, &quot;*.txt&quot;))
{

    string firstLine = new StreamReader(file).Using(f =&gt; f.ReadLine());
    Console.WriteLine(firstLine);
}
</pre>
<p>We’re reading the first line of every file and making sure the file gets closed immediately afterwards. The extension method takes care of disposing the <code>StreamReader</code>, and allows you to focus on the functionality rather than the implementation.</p>
<p>That’s what functional programming is all about!</p>
<p><strong>Extension method follows:</strong></p>
<pre class="brush: csharp;">public static class DisposableExtensions
{
   /// &lt;summary&gt;
   /// Runs a delegate on the specified &lt;see cref=&quot;IDisposable&quot;/&gt; and returns its value.
   /// &lt;/summary&gt;
   /// &lt;typeparam name=&quot;T&quot;&gt;Type of the object implementing &lt;see cref=&quot;IDisposable&quot;/&gt;&lt;/typeparam&gt;
   /// &lt;typeparam name=&quot;TOut&quot;&gt;The type of the return value.&lt;/typeparam&gt;
   /// &lt;param name=&quot;disposable&quot;&gt;The object implementing &lt;see cref=&quot;IDisposable&quot;/&gt;.&lt;/param&gt;
   /// &lt;param name=&quot;func&quot;&gt;A delegate that takes &lt;paramref name=&quot;disposable&quot;/&gt; as a parameter and returns a value.&lt;/param&gt;
   /// &lt;returns&gt;Value returned by &lt;paramref name=&quot;func&quot;/&gt; delegate.&lt;/returns&gt;
   public static TOut Using&lt;T, TOut&gt;(this T disposable, Func&lt;T, TOut&gt; func) where T : IDisposable
   {
       using (disposable)
       {
           return func(disposable);
       }
   }

   /// &lt;summary&gt;
   /// Runs a delegate on the specified &lt;see cref=&quot;IDisposable&quot;/&gt; and does not return anything.
   /// &lt;/summary&gt;
   /// &lt;typeparam name=&quot;T&quot;&gt;Type of the object implementing &lt;see cref=&quot;IDisposable&quot;/&gt;&lt;/typeparam&gt;
   /// &lt;param name=&quot;disposable&quot;&gt;The object implementing &lt;see cref=&quot;IDisposable&quot;/&gt;.&lt;/param&gt;
   /// &lt;param name=&quot;action&quot;&gt;A delegate that takes &lt;paramref name=&quot;disposable&quot;/&gt; as a parameter.&lt;/param&gt;
   public static void Using&lt;T&gt;(this T disposable, Action&lt;T&gt; action) where T : IDisposable
   {
       using (disposable)
       {
           action(disposable);
       }
   }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.whycantyoucode.com/2009/11/extension-method-of-the-day-inline-using-block-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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 to [...]]]></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>1</slash:comments>
		</item>
	</channel>
</rss>
