<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-8715120618224381002</id><updated>2011-12-15T05:49:06.357Z</updated><category term='LINQ'/><category term='DSLs'/><category term='threads'/><category term='stored procedures'/><category term='javascript'/><category term='lambdas'/><category term='foreach'/><category term='debugging'/><category term='dynamic'/><category term='immutable'/><category term='games'/><category term='monads'/><category term='rdbms'/><category term='delegates'/><category term='state'/><category term='regions'/><category term='C++'/><category term='C#'/><category term='Interop'/><category term='IDisposable'/><category term='expressions'/><category term='COIL'/><category term='generics'/><category term='wish'/><category term='value types'/><category term='yield return'/><category term='testing'/><category term='architecture'/><category term='WPF'/><category term='ora'/><category term='BCL'/><category term='nhibernate'/><category term='.NET'/><category term='C# 4.0'/><title type='text'>This is an EX blog...</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>46</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-999614234327595394</id><published>2009-06-09T11:37:00.002+01:00</published><updated>2011-02-04T11:09:43.422Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='value types'/><category scheme='http://www.blogger.com/atom/ns#' term='yield return'/><title type='text'>Generic Value Object With Yield Return</title><content type='html'>&lt;p&gt;Inspired by &lt;a href="http://elegantcode.com/2009/06/07/generic-value-object/"&gt;this&lt;/a&gt; and &lt;a href="http://grabbagoft.blogspot.com/2007/06/generic-value-object-equality.html"&gt;this&lt;/a&gt;, here's my version.&lt;/p&gt;  &lt;p class="under"&gt;&lt;span class="author"&gt;&lt;a title="Posts by Jan Van Ryswyck" href="http://elegantcode.com/author/jryswyck/"&gt;&lt;span &gt;Jan Van Ryswyck&lt;/span&gt;&lt;/a&gt; is right to use static reflection, and to do that he "registers" the properties in a list. &lt;/span&gt;&lt;span class="author"&gt;On the other hand, a&lt;/span&gt;ssuming you'd have a lot of these objects building up in the GC, it might prove important to reduce the number of ancillary allocations going on, so it may be better to avoid creating a list of the properties in every single instance.&lt;/p&gt;  &lt;p class="under"&gt;It's not really necessary to have the full information about the properties via reflection; we only need the values. Also it's a pain to have to distinguish between fields and properties. Finally, we are really doing operations on a sequence of values, which can be expressed very neatly with Linq operators, and specified in the derived class with an iterator method.&lt;/p&gt;  &lt;p class="under"&gt;So here's what I came up with:&lt;/p&gt;  &lt;div&gt;   &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;abstract&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; ValueObject&amp;lt;T&amp;gt; : IEquatable&amp;lt;T&amp;gt;
   where T : ValueObject&amp;lt;T&amp;gt;
{
   &lt;span style="color: #0000ff"&gt;protected&lt;/span&gt; &lt;span style="color: #0000ff"&gt;abstract&lt;/span&gt; IEnumerable&amp;lt;&lt;span style="color: #0000ff"&gt;object&lt;/span&gt;&amp;gt; Reflect();

   &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;override&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; Equals(Object obj)
   {
       &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (ReferenceEquals(&lt;span style="color: #0000ff"&gt;null&lt;/span&gt;, obj)) &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;false&lt;/span&gt;;
       &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (obj.GetType() != GetType()) &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;false&lt;/span&gt;;
       &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Equals(obj &lt;span style="color: #0000ff"&gt;as&lt;/span&gt; T);
   }

   &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; Equals(T other)
   {
       &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (ReferenceEquals(&lt;span style="color: #0000ff"&gt;null&lt;/span&gt;, other)) &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;false&lt;/span&gt;;
       &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (ReferenceEquals(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt;, other)) &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;true&lt;/span&gt;;
       &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Reflect().SequenceEqual(other.Reflect());
   }

   &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;override&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; GetHashCode()
   {
       &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Reflect().Aggregate(36, (hashCode, value) =&amp;gt; value == &lt;span style="color: #0000ff"&gt;null&lt;/span&gt; ?
                               hashCode : hashCode ^ value.GetHashCode());
   }

   &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;override&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; ToString()
   {
       &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #006080"&gt;"{ "&lt;/span&gt; + (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;) Reflect().Aggregate((l, r) =&amp;gt; l + &lt;span style="color: #006080"&gt;", "&lt;/span&gt; + r) + &lt;span style="color: #006080"&gt;" }"&lt;/span&gt;;
   }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p class="under"&gt;First off, it's a lot shorter! Aside from the standard &lt;strong&gt;ReferenceEquals&lt;/strong&gt; checks, every method is a one-liner, a return of a single expression. Check out how &lt;strong&gt;SequenceEqual&lt;/strong&gt; does so much work for us. And &lt;strong&gt;Aggregate&lt;/strong&gt; is designed for turning a sequence into one value, which is exactly what &lt;strong&gt;GetHashCode&lt;/strong&gt; and &lt;strong&gt;ToString&lt;/strong&gt; are all about.&lt;/p&gt;

&lt;p class="under"&gt;This is all possible because we're treating the properties or fields as just a sequence of values, obtained from the &lt;strong&gt;Reflect&lt;/strong&gt; method, which the derived class has to supply.&lt;/p&gt;

&lt;p class="under"&gt;(You could easily add &lt;strong&gt;operator==&lt;/strong&gt; and &lt;strong&gt;operator!=&lt;/strong&gt; of course. Also in case you're wondering about the way &lt;strong&gt;ToString&lt;/strong&gt; appears not to check for &lt;strong&gt;null&lt;/strong&gt;, actually it does, because one odd thing about .NET is that string concatenation can cope with &lt;strong&gt;null&lt;/strong&gt; strings.)&lt;/p&gt;

&lt;p class="under"&gt;Secondly, the way you use it is pretty neat as well:&lt;/p&gt;

&lt;div&gt;
 &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Person : ValueObject&amp;lt;Person&amp;gt;
{
   &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; Age { get; set; }
   &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Name { get; set; }

   &lt;span style="color: #0000ff"&gt;protected&lt;/span&gt; &lt;span style="color: #0000ff"&gt;override&lt;/span&gt; IEnumerable&amp;lt;&lt;span style="color: #0000ff"&gt;object&lt;/span&gt;&amp;gt; Reflect()
   {
       &lt;span &gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Age;
       &lt;span &gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Name;
   }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p class="under"&gt;It wouldn't matter if I yielded the values of fields or properties, and there's no need for expression-lambda trickery to get a &lt;strong&gt;PropertyInfo&lt;/strong&gt;.&lt;/p&gt;

&lt;p class="under"&gt;If you're unfamiliar with how iterator methods work, you may be wondering, what if I have twenty fields and the first fields of two instances are unequal, isn't this going to waste time comparing the other nineteen fields? No, because &lt;strong&gt;SequenceEqual&lt;/strong&gt; will stop iterating as soon as it finds an unequal element pair, and iterator methods are interruptible.&lt;/p&gt;

&lt;p class="under"&gt;(Note that if you need this to work on .NET 2.0, you can grab &lt;a href="http://code.msdn.microsoft.com/BclExtras"&gt;Jared Parsons' BCL Extras&lt;/a&gt; library to get the necessary sequence operations. If you're using the C# 2.0 compiler you just need to rejig the method call syntax to avoid using them as extension methods. Iterator methods were already available in 2.0, so nothing here is dependent on 3.0.)&lt;/p&gt;  

&lt;script&gt;location='http://smellegantcode.wordpress.com/2009/06/09/generic-value-object-with-yield-return/'&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-999614234327595394?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/999614234327595394/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=999614234327595394' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/999614234327595394'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/999614234327595394'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/06/generic-value-object-with-yield-return.html' title='Generic Value Object With Yield Return'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-3389000149127539717</id><published>2009-06-04T11:34:00.002+01:00</published><updated>2011-02-04T11:10:45.831Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambdas'/><category scheme='http://www.blogger.com/atom/ns#' term='yield return'/><title type='text'>Lazy Sequence Generation without using Yield Return</title><content type='html'>&lt;p&gt;C# has the yield return feature, which makes it easy to write state machines as if they were plain old methods:&lt;/p&gt;  &lt;div&gt;   &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Program
{
    &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; IEnumerable&amp;lt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt;&amp;gt; SomeNumbers()
    {
        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Started&amp;quot;&lt;/span&gt;);

        yield &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 1;
        
        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Yielded 1&amp;quot;&lt;/span&gt;);

        yield &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 2;
            
        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Yielded 2&amp;quot;&lt;/span&gt;);

        yield &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 3;

        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Finished&amp;quot;&lt;/span&gt;);
    }

    &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Main(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; n &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; SomeNumbers())
        {
            Console.WriteLine(n);
        }
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The output shows that the sequence of numbers is generated &amp;quot;lazily&amp;quot;, with each chunk of code in the method being executed only on demand as the &lt;strong&gt;foreach&lt;/strong&gt; pulls values from sequence.&lt;/p&gt;

&lt;p&gt;How close can we get to this using only lamdbas? Pretty close:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Program
{
    &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; Lazy.Yielding&amp;lt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt;&amp;gt; SomeNumbers()
    {
        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Started&amp;quot;&lt;/span&gt;);

        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Lazy.Yield(1, () =&amp;gt; {

        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Yielded 1&amp;quot;&lt;/span&gt;);

        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Lazy.Yield(2, () =&amp;gt; {
        
        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Yielded 2&amp;quot;&lt;/span&gt;);

        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Lazy.Yield(3, () =&amp;gt; {

        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Finished&amp;quot;&lt;/span&gt;);

        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;; }); }); });
    }

    &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Main(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; n &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; Lazy.Enumerate&amp;lt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt;&amp;gt;(SomeNumbers))
        {
            Console.WriteLine(n);
        }
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;By messing with the nesting of my curly braces, I've made it look like the original, but really it's made of three nested lambdas. So this version of &lt;strong&gt;SomeNumbers&lt;/strong&gt; is, deep breath... a function that returns a function that returns a function that returns a function.&lt;/p&gt;

&lt;p&gt;Each returned function supplies the code to execute for the next step.&lt;/p&gt;

&lt;p&gt;The main remaining ingredient is a helper function &lt;strong&gt;Lazy.Enumerate&lt;/strong&gt; that turns our strange contraption into a plain &lt;strong&gt;IEnumerable&lt;/strong&gt;, so we can loop through it conveniently.&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Lazy
{
    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Yielding&amp;lt;T&amp;gt;
    {
        &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;readonly&lt;/span&gt; T Result;
        &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;readonly&lt;/span&gt; Func&amp;lt;Yielding&amp;lt;T&amp;gt;&amp;gt; Next;

        &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Yielding(T result)
        {
            Result = result;
            Next = &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;;
        }

        &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Yielding(T result, Func&amp;lt;Yielding&amp;lt;T&amp;gt;&amp;gt; next)
        {
            Result = result;
            Next = next;
        }
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; Yielding&amp;lt;T&amp;gt; Yield&amp;lt;T&amp;gt;(T value, Func&amp;lt;Yielding&amp;lt;T&amp;gt;&amp;gt; next)
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Yielding&amp;lt;T&amp;gt;(value, next);
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; Yielding&amp;lt;T&amp;gt; Yield&amp;lt;T&amp;gt;(T value)
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Yielding&amp;lt;T&amp;gt;(value);
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Seq&amp;lt;T&amp;gt; : IEnumerable&amp;lt;T&amp;gt;
    {
        &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;readonly&lt;/span&gt; Func&amp;lt;Yielding&amp;lt;T&amp;gt;&amp;gt; _generator;

        &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Seq(Func&amp;lt;Yielding&amp;lt;T&amp;gt;&amp;gt; generator)
        {
            _generator = generator;
        }

        &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Iter : IEnumerator&amp;lt;T&amp;gt;
        {
            &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; Func&amp;lt;Yielding&amp;lt;T&amp;gt;&amp;gt; _generator;

            &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Iter(Func&amp;lt;Yielding&amp;lt;T&amp;gt;&amp;gt; generator)
            {
                _generator = generator;
            }

            &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; T Current { get; set; }

            &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Dispose() { }

            &lt;span style="color: #0000ff"&gt;object&lt;/span&gt; System.Collections.IEnumerator.Current
            {
                get { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Current; }
            }

            &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; MoveNext()
            {
                &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (_generator == &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)
                    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;false&lt;/span&gt;;

                Yielding&amp;lt;T&amp;gt; yielding = _generator();
                &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (yielding == &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)
                {
                    _generator = &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;;
                    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;false&lt;/span&gt;;
                }

                Current = yielding.Result;
                _generator = yielding.Next;
                &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;true&lt;/span&gt;;
            }

            &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Reset()
            {
                &lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; NotImplementedException();
            }
        }

        &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; IEnumerator&amp;lt;T&amp;gt; GetEnumerator()
        {
            &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Iter(_generator);
        }

        System.Collections.IEnumerator 
            System.Collections.IEnumerable.GetEnumerator()
        {
            &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; GetEnumerator();
        }
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; Enumerate&amp;lt;T&amp;gt;(
                      Func&amp;lt;Yielding&amp;lt;T&amp;gt;&amp;gt; generator)
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Seq&amp;lt;T&amp;gt;(generator);
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Most of the code is &amp;quot;boilerplate&amp;quot; implementation of &lt;strong&gt;IEnumerable&lt;/strong&gt;/&lt;strong&gt;IEnumerator&lt;/strong&gt;. The important bit is the &lt;strong&gt;MoveNext&lt;/strong&gt; method, which calls the generator method to get the next value &lt;em&gt;and&lt;/em&gt; the next generator method.&lt;/p&gt;

&lt;p&gt;So what's missing? The major thing (aside from the misery of getting the syntax right, closing all the right brackets, etc.) is the lack of &lt;strong&gt;try&lt;/strong&gt;/&lt;strong&gt;finally&lt;/strong&gt; support, which turns out to be extremely useful. We could add support for that, however. Firstly, we'd add this member to &lt;strong&gt;Yielding&lt;/strong&gt;.&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;readonly&lt;/span&gt; Action Finally;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The generator code would initialize that field to whatever action it liked, to represent the &lt;strong&gt;finally&lt;/strong&gt; block, before returning the &lt;strong&gt;Yielding&lt;/strong&gt; instance. And &lt;strong&gt;Lazy.Seq.Iter&lt;/strong&gt; would store it so it could execute it before retrieving the next value, and it would also execute it from the &lt;strong&gt;Dispose&lt;/strong&gt; method, so that the &lt;strong&gt;Finally&lt;/strong&gt; action would run even if the loop was abandoned.&lt;/p&gt;  


&lt;script&gt;location='http://smellegantcode.wordpress.com/2009/06/04/lazy-sequence-generation-without-using-yield-return/'&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-3389000149127539717?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/3389000149127539717/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=3389000149127539717' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/3389000149127539717'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/3389000149127539717'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/06/lazy-sequence-generation-without-using.html' title='Lazy Sequence Generation without using Yield Return'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-3861584726507616259</id><published>2009-05-22T13:56:00.003+01:00</published><updated>2011-02-04T11:11:26.362Z</updated><title type='text'>VC++16 has decltype in Beta 1 (so Linq to C++0x looks a little nicer)</title><content type='html'>This post has moved to my new(er) blog and can be found here:

&lt;a href="http://smellegantcode.wordpress.com/2009/05/22/vc16-has-decltype-in-beta-1-so-linq-to-c0x-looks-a-little-nicer/"&gt;http://smellegantcode.wordpress.com/2009/05/22/vc16-has-decltype-in-beta-1-so-linq-to-c0x-looks-a-little-nicer/&lt;/a&gt;

&lt;p&gt;&lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2009/01/linq-to-c0x.html"&gt;A while ago I wrote up a little demo&lt;/a&gt; of using lambdas to implement convenient lazy list comprehension in C++0x, but at the time the VC++ compiler I was using lacked &lt;code&gt;decltype&lt;/code&gt;, and I found a need for it.&lt;/p&gt;  &lt;p&gt;I just tried out the Beta 1 that was released this week, and it has &lt;code&gt;decltype&lt;/code&gt;, so here's the updated sample:&lt;/p&gt;  &lt;div&gt;   &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
#include &amp;lt;sstream&amp;gt;

&lt;span style="color: #008000"&gt;// Some helpers for working with decltype &lt;/span&gt;
&lt;span style="color: #008000"&gt;// (maybe these are in std:: somewhere?)&lt;/span&gt;
template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; T&amp;gt;
T *make_ptr() { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; (T *)0; }

template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; T&amp;gt;
&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; T &amp;amp;make_ref() { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; *(make_ptr&amp;lt;T&amp;gt;()); }

&lt;span style="color: #008000"&gt;// so you don't need to obtain boost::lexical_cast!&lt;/span&gt;
template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; T&amp;gt;
std::&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; to_string(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; T &amp;amp;v)
{
    std::ostringstream s;
    s &amp;lt;&amp;lt; v;
    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; s.str();
}

&lt;span style="color: #008000"&gt;// Unary function that always returns true&lt;/span&gt;
template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; T&amp;gt;
&lt;span style="color: #0000ff"&gt;struct&lt;/span&gt; always_true
{
    &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;() (&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; T &amp;amp;) &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;true&lt;/span&gt;; }
};

&lt;span style="color: #008000"&gt;// Unary function that returns its argument&lt;/span&gt;
template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; T&amp;gt;
&lt;span style="color: #0000ff"&gt;struct&lt;/span&gt; pass_thru
{
    T &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;() (&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; T &amp;amp;e) &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; e; }
};

template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TElemFrom, 
          &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TElemTo, 
          &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TIterFrom, 
          &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TSelector,
          &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TPredicate&amp;gt;
&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; filter
{
    TIterFrom from_;
    TIterFrom end_;
    &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TSelector &amp;amp;selector_;
    &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TPredicate &amp;amp;predicate_;

&lt;span style="color: #0000ff"&gt;public&lt;/span&gt;:
    filter(TIterFrom from, TIterFrom end, 
             &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TSelector &amp;amp;selector, 
             &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TPredicate &amp;amp;predicate)
        : from_(from), end_(end), 
          selector_(selector), 
          predicate_(predicate) {}

    &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; const_iterator
    {
        TIterFrom from_;
        TIterFrom end_;
        &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TSelector &amp;amp;selector_;
        &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TPredicate &amp;amp;predicate_;

        &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; locate()
        {
            &lt;span style="color: #0000ff"&gt;while&lt;/span&gt; (!done())
            {
                &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (predicate_(*from_))
                    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt;;

                ++from_;
            }
        }

        &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; done() &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; (from_ == end_); }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt;:
        const_iterator(TIterFrom from, TIterFrom end, 
                       &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TSelector &amp;amp;selector,
                       &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TPredicate &amp;amp;predicate)
            : from_(from), end_(end), 
              selector_(selector),
              predicate_(predicate) { locate(); }

        TElemTo &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;*() &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; selector_(*from_); }

        const_iterator &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;++()
        {
            ++from_;
            locate();
            &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; *&lt;span style="color: #0000ff"&gt;this&lt;/span&gt;;
        }

        &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;==(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; const_iterator &amp;amp;other) &lt;span style="color: #0000ff"&gt;const&lt;/span&gt;
            { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; done() &amp;amp;&amp;amp; other.done(); }

        &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;!=(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; const_iterator &amp;amp;other) &lt;span style="color: #0000ff"&gt;const&lt;/span&gt;
            { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; !done() || !other.done(); }
    };

    typedef TElemFrom value_type;

    const_iterator begin() &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; 
        { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; const_iterator(from_, end_, selector_, predicate_); }

    const_iterator end() &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; 
        { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; const_iterator(end_, end_, selector_, predicate_); }

    template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TSelector&amp;gt;
    filter&amp;lt;TElemTo, 
             decltype(make_ref&amp;lt;TSelector&amp;gt;()(make_ref&amp;lt;TElemTo&amp;gt;())),
             const_iterator, 
             TSelector,
             always_true&amp;lt;TElemTo&amp;gt; &amp;gt;
        select(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TSelector &amp;amp;selector)
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; filter&amp;lt;TElemTo, 
            decltype(make_ref&amp;lt;TSelector&amp;gt;()(make_ref&amp;lt;TElemTo&amp;gt;())), 
                      const_iterator, 
                      TSelector, 
                      always_true&amp;lt;TElemTo&amp;gt; &amp;gt;
                    (begin(), 
                     end(), 
                     selector, 
                     always_true&amp;lt;TElemTo&amp;gt;());
    }

    template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TPredicate&amp;gt;
    filter&amp;lt;TElemTo, 
              TElemTo,
             const_iterator, 
             pass_thru&amp;lt;TElemTo&amp;gt;, 
             TPredicate&amp;gt; 
        where(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TPredicate &amp;amp;predicate)
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; filter&amp;lt;TElemTo, 
                        TElemTo,
                        const_iterator, 
                        pass_thru&amp;lt;TElemTo&amp;gt;, 
                        TPredicate&amp;gt;
                    (begin(),
                     end(),
                     pass_thru&amp;lt;TElemTo&amp;gt;(), 
                     predicate);
    }
};

template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TCollFrom&amp;gt;
filter&amp;lt;typename TCollFrom::value_type, 
         typename TCollFrom::value_type,
         typename TCollFrom::const_iterator, 
         pass_thru&amp;lt;typename TCollFrom::value_type&amp;gt;,
         always_true&amp;lt;typename TCollFrom::value_type&amp;gt; &amp;gt;
    from(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TCollFrom &amp;amp;from)
{
    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; filter&amp;lt;typename TCollFrom::value_type, 
                    typename TCollFrom::value_type, 
                    typename TCollFrom::const_iterator, 
                    pass_thru&amp;lt;typename TCollFrom::value_type&amp;gt;, 
                    always_true&amp;lt;typename TCollFrom::value_type&amp;gt; &amp;gt;
                (from.begin(), 
                 from.end(), 
                 pass_thru&amp;lt;typename TCollFrom::value_type&amp;gt;(), 
                 always_true&amp;lt;typename TCollFrom::value_type&amp;gt;());
}

&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; main(&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; argc, &lt;span style="color: #0000ff"&gt;char&lt;/span&gt;* argv[])
{
    std::vector&amp;lt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt;&amp;gt; vecInts;
    vecInts.push_back(5);
    vecInts.push_back(2);
    vecInts.push_back(9);

    auto filtered = from(vecInts)
        .where([] (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; n) { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; n &amp;gt; 3; })
        .select([] (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; n) { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #006080"&gt;&amp;quot;\&amp;quot;&amp;quot;&lt;/span&gt; + to_string(n) + &lt;span style="color: #006080"&gt;&amp;quot;\&amp;quot;&amp;quot;&lt;/span&gt;; });

    &lt;span style="color: #0000ff"&gt;for&lt;/span&gt; (auto i = filtered.begin(); i != filtered.end(); ++i)
        std::cout &amp;lt;&amp;lt; *i &amp;lt;&amp;lt; std::endl;

    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 0;
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The main function is the pay-off, of course. I have a vector of &lt;code&gt;ints&lt;/code&gt;, and I wrap it something that ends up stored in a variable called &lt;font face="Courier New"&gt;filtered&lt;/font&gt;, which I can then iterate through. The filtering (discarding anything not greater than 3) and transforming (&lt;font face="Courier New"&gt;int&lt;/font&gt; to quoted &lt;font face="Courier New"&gt;string&lt;/font&gt;) of the items happens on-the-fly during that iteration.&lt;/p&gt;

&lt;p&gt;(And to clarify, this is different from the last time I posted it because &lt;code&gt;select&lt;/code&gt; no longer requires any type parameters to be explicitly given - thanks to &lt;code&gt;decltype&lt;/code&gt;).&lt;/p&gt;

&lt;script&gt;location='http://smellegantcode.wordpress.com/2009/05/22/vc16-has-decltype-in-beta-1-so-linq-to-c0x-looks-a-little-nicer/'&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-3861584726507616259?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/3861584726507616259/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=3861584726507616259' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/3861584726507616259'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/3861584726507616259'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/05/vc16-has-decltype-in-beta-1-so-linq-to.html' title='VC++16 has decltype in Beta 1 (so Linq to C++0x looks a little nicer)'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-5234968457644923912</id><published>2009-05-14T11:38:00.002+01:00</published><updated>2011-02-04T11:11:57.122Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='state'/><title type='text'>Recovery</title><content type='html'>&lt;p&gt;If you want your application to be able to recover from a crash, it would NOT be ideal for it to restore the exact state it was in immediately before the crash, because then it would just crash again.&lt;/p&gt;  &lt;p&gt;(Same goes for economies, presumably).&lt;/p&gt;  

&lt;script&gt;location='http://smellegantcode.wordpress.com/2009/05/14/recovery/'&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-5234968457644923912?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/5234968457644923912/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=5234968457644923912' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/5234968457644923912'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/5234968457644923912'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/05/recovery.html' title='Recovery'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-2524250418604219033</id><published>2009-05-11T11:09:00.002+01:00</published><updated>2011-02-04T11:12:20.087Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='stored procedures'/><category scheme='http://www.blogger.com/atom/ns#' term='nhibernate'/><category scheme='http://www.blogger.com/atom/ns#' term='architecture'/><category scheme='http://www.blogger.com/atom/ns#' term='rdbms'/><title type='text'>When to use Stored Procedures?</title><content type='html'>&lt;script&gt;location='http://smellegantcode.wordpress.com/2009/05/11/when-to-use-stored-procedures/'&lt;/script&gt;


&lt;p&gt;No coding blog would be complete without an overly-simplistic salvo fired into this bloody online battlefield, so here's mine.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;What if you're writing an application that will make heavy use of an RDBMS?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;If you're writing an packaged app for sale to customers who want to run it on the RDBMS of their choice, &lt;em&gt;don't use stored procedures.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;But what if you're writing something bespoke?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Maybe you've never in practice had to change RDBMS in mid-project. But maybe that's because you automatically ruled it out as an impossibility - how do you know what advantages you might have had, what client license bundle offers you could have benefitted from, if you maintained the ability to switch RDBMS vendors on a whim? Competition pressure is what keeps vendors competitive, and competition pressure disappears if customers lose the ability to switch. The vendors know this, which is why they want to lock you in. So if you want to be able to get the best deal out of RDBMS vendors, &lt;em&gt;don't use stored procedures.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;But what if you want to have a layered architecture?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Adding more languages doesn't enable more layers. It just adds more development cost. You can write a data access abstraction layer in any language - and in Java and .NET, open source toolkits like [n]Hibernate already make this child's play, largely eliminating the need to generate your own SQL strings or DDL.&lt;/p&gt;  &lt;p&gt;If you want to reduce development costs by keeping the number of language skills required to maintain an app lower, by writing all business logic and data layer logic in one language, &lt;em&gt;don't use stored procedures&lt;/em&gt;.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;But what if you're prepared to take on extra cost because you want to optimise by moving execution into the RDBMS? &lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;If you haven't yet done any comparative profiling to establish where such optimisation is really needed or makes any measurable difference, &lt;em&gt;don't use stored procedures&lt;/em&gt;.&lt;/p&gt;  &lt;p&gt;... otherwise, knock yourself out!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-2524250418604219033?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/2524250418604219033/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=2524250418604219033' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/2524250418604219033'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/2524250418604219033'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/05/when-to-use-stored-procedures.html' title='When to use Stored Procedures?'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-1889147315173258682</id><published>2009-03-29T15:48:00.004+01:00</published><updated>2011-02-04T11:12:53.653Z</updated><title type='text'>General form of C# Object Initializers</title><content type='html'>&lt;script&gt;location='http://smellegantcode.wordpress.com/2009/03/29/general-form-of-c-object-initializers/'&lt;/script&gt;

&lt;p&gt;C# has a language feature that allows several properties of an object to be assigned to as a suffix to a &lt;code&gt;new&lt;/code&gt; expression, namely the &lt;i&gt;object initializer&lt;/i&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var myObj = new MyClass
            {
                SomeProperty = 5,
                Another = true,
                Complain = str =&amp;gt; MessageBox.Show(str),
            };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As properties can have hand-coded setters, this is an opportunity to call several methods on the newly constructed object, without having to make each method return the same object.&lt;/p&gt;
&lt;p&gt;The limitations on property setters are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;They can only accept one argument&lt;/li&gt;
&lt;li&gt;They cannot be generic&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I would like it if we could call methods and enlist in events, as well as assign to properties, inside an object initializer block.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var myObj = new MyClass
            {
                SomeProperty = 5,
                Another = true,
                Complain = str =&amp;gt; MessageBox.Show(str),
                DoSomething(),
                Click += (se, ev) =&amp;gt; MessageBox.Show("Clicked!"),
            };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And why should such a block of modifications only be applicable immediately after construction? We could have:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;myObj with
{
    SomeProperty = 5,
    Another = true,
    Complain = str =&amp;gt; MessageBox.Show(str),
    DoSomething(),
    Click += (se, ev) =&amp;gt; MessageBox.Show("Clicked!"),
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;with&lt;/code&gt; would be a new keyword that operates on an object of some type and produces the same object and type - note that this would be an &lt;em&gt;expression&lt;/em&gt;, not a &lt;em&gt;statement&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;So you could use initializer-style syntax regardless of whether you'd got the object from a &lt;code&gt;new&lt;/code&gt; expression or from an IOC or factory method, etc.&lt;/p&gt;
&lt;p&gt;In fact you could use &lt;code&gt;with&lt;/code&gt; after a complete &lt;code&gt;new&lt;/code&gt; and it would be equivalent to the current style of object initializer:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var myObj = new MyClass() with
            {
                SomeProperty = 5,
                Another = true,
                Complain = str =&amp;gt; MessageBox.Show(str),
                DoSomething(),
                Click += (se, ev) =&amp;gt; MessageBox.Show("Clicked!")
            };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I mused about this &lt;a href="http://stackoverflow.com/questions/688418/what-fluent-interfaces-have-you-made-or-seen-in-c-that-were-very-valuable-what/691272#691272"&gt;in a Stack Overflow answer&lt;/a&gt;, and &lt;a href="http://stackoverflow.com/users/80112/charlie-flowers"&gt;Charlie Flowers&lt;/a&gt; pointed out something I should have realised immediately - we can implement with as an extension method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static T With(this T with, Action&amp;lt;T&amp;gt; action)
{
    if (with != null)
        action(with);
    return with;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Equivalent of normal object initializer, but with event enlisting:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var myObj = new MyClass().With(w =&amp;gt;
            {
                w.SomeProperty = 5;
                w.Another = true;
                w.Click += (se, ev) =&amp;gt; MessageBox.Show("Clicked!");
            };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And on a factory method instead of a &lt;code&gt;new&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var myObj = Factory.Alloc().With(w =&amp;gt;
            {
                w.SomeProperty = 5;
                w.Another = true;
                w.Click += (se, ev) =&amp;gt; MessageBox.Show("Clicked!");
            };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I couldn't resist giving it the "maybe monad"-style check for null as well, so if you have something that might return &lt;code&gt;null&lt;/code&gt;, you can still apply &lt;code&gt;With&lt;/code&gt; to it and then check it for &lt;code&gt;null&lt;/code&gt;-ness.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-1889147315173258682?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/1889147315173258682/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=1889147315173258682' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/1889147315173258682'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/1889147315173258682'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/03/general-form-of-c-object-initializers.html' title='General form of C# Object Initializers'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-4918019411433582146</id><published>2009-03-06T10:30:00.002Z</published><updated>2011-02-04T11:13:33.026Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='threads'/><category scheme='http://www.blogger.com/atom/ns#' term='immutable'/><title type='text'>Readonly Fields and Thread Safety</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/03/06/readonly-fields-and-thread-safety/'&lt;/script&gt;

&lt;p&gt;In C# you can mark the fields of a type as &lt;strong&gt;readonly&lt;/strong&gt; (indeed you generally should if it's a &lt;strong&gt;struct&lt;/strong&gt;). By doing so, you make it illegal to change the fields except in a constructor of the type.&lt;/p&gt;  &lt;p&gt;The advantage of this is that &lt;strong&gt;readonly&lt;/strong&gt; data can be shared freely between threads without any thread causing updates that may be seen &amp;quot;in progress&amp;quot; by other threads, simply because there never will be any updates.&lt;/p&gt;  &lt;p&gt;But is this strictly speaking true? Nope. It would be true if it were impossible for another thread to gain access to a partially constructed object. This seems true at first because the constructor of an object effectively &amp;quot;returns&amp;quot; a reference to itself via the &lt;strong&gt;new&lt;/strong&gt; operator, which then becomes available to the caller of &lt;strong&gt;new&lt;/strong&gt;, at which point the object is available to be passed around and is also fully constructed.&lt;/p&gt;  &lt;p&gt;But a constructor can call methods, and it can pass &lt;strong&gt;this&lt;/strong&gt; to methods. Those methods could pass that information to other threads. So you have to be careful what you do in a constructor. Maybe the compiler will help to check this somehow in a future version of the language.&lt;/p&gt;  &lt;p&gt;This ties in nicely with some general advice about constructors that &lt;a href="http://blogs.msdn.com/brada/"&gt;Brad Abrams&lt;/a&gt; gives in the &lt;a href="http://www.amazon.co.uk/Programming-Language-Annotated-Microsoft-Development/dp/0321562992"&gt;Annotated C# Programming Language&lt;/a&gt;: do as little as possible in the constructor, and do everything else &amp;quot;lazily&amp;quot; - that is, the first time you need it. If you find yourself requiring non-&lt;strong&gt;readonly&lt;/strong&gt; fields to achieve that, then you potentially have a problem with your design, because your class as a whole is not going to be &lt;strong&gt;readonly&lt;/strong&gt; and so will not be trivially shareable in the way you originally assumed.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-4918019411433582146?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/4918019411433582146/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=4918019411433582146' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/4918019411433582146'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/4918019411433582146'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/03/readonly-fields-and-thread-safety.html' title='Readonly Fields and Thread Safety'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-5846098229299972453</id><published>2009-03-04T23:31:00.001Z</published><updated>2009-03-10T11:32:08.054Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='games'/><title type='text'>JavaScript Invaders!</title><content type='html'>&lt;p&gt;Click in the small text field in the top left corner to give allow the game to receive keyboard events.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Z = left &lt;/li&gt;    &lt;li&gt;X = right &lt;/li&gt;    &lt;li&gt;M = fire &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;/p&gt; &lt;iframe src="http://www.earwicker.com/invaders/invaders.html" width="300" scrolling="no" height="340"&gt;&lt;p&gt;&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;&lt;/iframe&gt;&lt;p&gt;&lt;/p&gt;  &lt;p&gt;Compatible with IE, Firefox and Safari, pure JavaScript and HTML&lt;/p&gt; &lt;p&gt;I wrote this during a train journey, just to see if it was practically possible. Only then did I google for other examples, and found quite a few going back years. &lt;a href="http://www.harryguillermo.com/games/pacman/pacman.php"&gt;This version of Pacman&lt;/a&gt; has excellent attention to detail.  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-5846098229299972453?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/5846098229299972453/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=5846098229299972453' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/5846098229299972453'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/5846098229299972453'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/03/javascript-invaders.html' title='JavaScript Invaders!'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-8259948088152602835</id><published>2009-03-01T17:16:00.002Z</published><updated>2011-02-04T11:14:27.625Z</updated><title type='text'>The Amazing Speed of the .NET Garbage Collector</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/03/01/the-amazing-speed-of-the-net-garbage-collector/'&lt;/script&gt;

&lt;p&gt;Coming from a C++ background, I always balk at designs that involve lots of small heap allocations. It’s something I’m gradually training myself to stop doing, because in managed code, it’s a completely irrational concern.&lt;/p&gt;  &lt;p&gt;Given the constant usefulness of lambdas for &lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2009/02/functional-replacement-for-using.html"&gt;things like this&lt;/a&gt;, it is worth reassuring myself (and others) that the overhead of such techniques is negligible. I already knew it probably was, but I had no idea just how negligible. It really is ridiculously unimportant.&lt;/p&gt;  &lt;p&gt;Here’s my simple test program – most of the operations it does are meaningless busywork (like a typical school day). The important thing is the difference between &lt;strong&gt;Foo1&lt;/strong&gt; and &lt;strong&gt;Foo2:&lt;/strong&gt;&lt;/p&gt;  &lt;div&gt;   &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Program
{
    &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;readonly&lt;/span&gt; Queue&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt; _q = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Queue&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;();

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; _c;

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Push() { _q.Enqueue(_c.ToString()); }
    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Pop() { _q.Dequeue(); }
    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Count() { _c++; }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; Foo1()
    {
        &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; x = 0;
        Push();
        Count();
        x++;
        Pop();
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; x;
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Gateway(Action a)
    {
        Push();
        a();
        Pop();
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; Foo2()
    {
        &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; x = 0;
        Gateway(() =&amp;gt;
                       {
                           Count();
                           x++;
                       });
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; x;
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;double&lt;/span&gt; Time(Action a)
    {
        Stopwatch s = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Stopwatch();
        s.Start();
        a();
        s.Stop();
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; s.ElapsedMilliseconds;
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Main(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;[] args)
    {
        _q.Enqueue(&lt;span style="color: #006080"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);
        _q.Enqueue(&lt;span style="color: #006080"&gt;&amp;quot;y&amp;quot;&lt;/span&gt;);
        _q.Enqueue(&lt;span style="color: #006080"&gt;&amp;quot;z&amp;quot;&lt;/span&gt;);

        &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; reps = 100000000;

        &lt;span style="color: #0000ff"&gt;double&lt;/span&gt; direct = Time(() =&amp;gt;
        {
            &lt;span style="color: #0000ff"&gt;for&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; n = 0; n &amp;lt; reps; n++)
                Foo1();
        });
        
        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Direct, &amp;quot;&lt;/span&gt; + reps + &lt;span style="color: #006080"&gt;&amp;quot; calls: &amp;quot;&lt;/span&gt; + direct / 1000 + &lt;span style="color: #006080"&gt;&amp;quot; s&amp;quot;&lt;/span&gt;);

        &lt;span style="color: #0000ff"&gt;double&lt;/span&gt; lambda = Time(() =&amp;gt;
        {
            &lt;span style="color: #0000ff"&gt;for&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; n = 0; n &amp;lt; reps; n++)
                Foo2();
        });

        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Lambda, &amp;quot;&lt;/span&gt; + reps + &lt;span style="color: #006080"&gt;&amp;quot; calls: &amp;quot;&lt;/span&gt; + lambda / 1000 + &lt;span style="color: #006080"&gt;&amp;quot; s&amp;quot;&lt;/span&gt;);

        &lt;span style="color: #0000ff"&gt;double&lt;/span&gt; overhead = (lambda - direct);
        &lt;span style="color: #0000ff"&gt;double&lt;/span&gt; percall = overhead / reps;

        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Overhead per call: &amp;quot;&lt;/span&gt; + percall * 1000000 + &lt;span style="color: #006080"&gt;&amp;quot; ns&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Foo1&lt;/strong&gt; calls &lt;strong&gt;Push&lt;/strong&gt;, &lt;strong&gt;Count&lt;/strong&gt; and &lt;strong&gt;Pop&lt;/strong&gt; and also fools around with a local variable, &lt;strong&gt;x&lt;/strong&gt;. Note that &lt;strong&gt;Push&lt;/strong&gt; and &lt;strong&gt;Pop&lt;/strong&gt; manipulate a queue of strings. The queue stays a constant length during the test, with newly allocated strings being inserted and old strings being removed, so the GC has some work to do. The reason I used a queue was so that the lifetimes of GC objects would not simply coincide with the stack of function calls, forcing the CLR (I vaguely assume) to truly allocate objects in Generation 0 instead of “cheating” and using the stack to store everything.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Foo2&lt;/strong&gt; does the same, but it does so via &lt;strong&gt;Gateway&lt;/strong&gt;. Also note that it captures the local variable &lt;strong&gt;x&lt;/strong&gt; in a closure, so it can be read and modified in &lt;strong&gt;Foo2&lt;/strong&gt; and in the nested lambda.&lt;/p&gt;

&lt;p&gt;This means that for every call to &lt;strong&gt;Foo2&lt;/strong&gt;, it is necessary to allocate two GC objects. Firstly, the closure is implemented by a compiler generated class, which would look like this:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;[CompilerGenerated]
&lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;sealed&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; &amp;lt;&amp;gt;c__DisplayClass1
{
    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; x;

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; &amp;lt;Foo2&amp;gt;b__0()
    {
        Program.Count();
        x++;
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The local variable &lt;strong&gt;x&lt;/strong&gt; has become a field of that class. So every time &lt;strong&gt;Foo2&lt;/strong&gt; is called, an instance of &lt;strong&gt;&amp;lt;&amp;gt;c__DisplayClass1&lt;/strong&gt; is allocated to store the variable &lt;strong&gt;x&lt;/strong&gt;. Then there’s the lambda, which has become the method &lt;strong&gt;&amp;lt;Foo2&amp;gt;b__0&lt;/strong&gt; of the class. In order to pass it to &lt;strong&gt;Gateway&lt;/strong&gt;, an instance of the &lt;strong&gt;Action&lt;/strong&gt; delegate must be created that has an &lt;strong&gt;Invoke&lt;/strong&gt; method that forwards to &lt;strong&gt;&amp;lt;Foo2&amp;gt;b__0&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;To confirm this, look at the IL for &lt;strong&gt;Foo2&lt;/strong&gt;:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;.method &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; hidebysig &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; int32 Foo2() cil managed
{
    .maxstack 3
    .locals init (
        [0] &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Program/&amp;lt;&amp;gt;c__DisplayClass1 CS$&amp;lt;&amp;gt;8__locals2)
    L_0000: newobj instance &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Program/&amp;lt;&amp;gt;c__DisplayClass1::.ctor()
    L_0005: stloc.0 
    L_0006: ldloc.0 
    L_0007: ldc.i4.0 
    L_0008: stfld int32 Program/&amp;lt;&amp;gt;c__DisplayClass1::x
    L_000d: ldloc.0 
    L_000e: ldftn instance &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Program/&amp;lt;&amp;gt;c__DisplayClass1::&amp;lt;Foo2&amp;gt;b__0()
    L_0014: newobj instance &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; [System.Core]System.Action::.ctor(&lt;span style="color: #0000ff"&gt;object&lt;/span&gt;, native &lt;span style="color: #0000ff"&gt;int&lt;/span&gt;)
    L_0019: call &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Program::Gateway(&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; [System.Core]System.Action)
    L_001e: ldloc.0 
    L_001f: ldfld int32 Program/&amp;lt;&amp;gt;c__DisplayClass1::x
    L_0024: ret 
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Sure enough, there are two calls to &lt;strong&gt;newobj&lt;/strong&gt; – the first one allocates the storage for the closure, the second allocates the &lt;strong&gt;Action&lt;/strong&gt; delegate. Compare this with the much cleaner-looking code for &lt;strong&gt;Foo1&lt;/strong&gt;:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;.method &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; hidebysig &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; int32 Foo1() cil managed
{
    .maxstack 2
    .locals init (
        [0] int32 x)
    L_0000: ldc.i4.0 
    L_0001: stloc.0 
    L_0002: call &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Program::Push()
    L_0007: call &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Program::Count()
    L_000c: ldloc.0 
    L_000d: ldc.i4.1 
    L_000e: add 
    L_000f: stloc.0 
    L_0010: call &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Program::Pop()
    L_0015: ldloc.0 
    L_0016: ret 
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;No allocations, just some method calls. So the overhead of &lt;strong&gt;Foo2&lt;/strong&gt; must be pretty big, right? Especially when those heap-allocated objects will need to be garbage-collected all the time. What if a lot of them build up? Won’t that put “pressure” on the GC and make everything grind to a halt?&lt;/p&gt;

&lt;p&gt;Well, try running the test program. It does a hundred million calls to &lt;strong&gt;Foo1&lt;/strong&gt;, and then the same number of calls to &lt;strong&gt;Foo2&lt;/strong&gt;. It then figures out the difference in the timings for these runs. On my VM of Windows XP running on a MacBook Pro, the output is:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;Direct, 100000000 calls: 27.209 s
Lambda, 100000000 calls: 33.515 s
Overhead per call: 63.06 ns&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Now, it’s customary with this kind of test to observe that 33 seconds is longer than 27 seconds and try to conclude something from that, like “lambdas make your code about 25% slower”. However, that would be completely stupid. The point is that the code in the test is doing very little, apart from keeping the GC a little busy, so that makes the overhead appear more significant than it would be in a real program. The important point is that it only took 6 seconds longer even though we are doing a &lt;em&gt;hundred million calls, &lt;/em&gt;i.e. the overhead per call is about 60 nanoseconds. Which is very, very small. Code that actually did something useful would make such an overhead utterly invisible.&lt;/p&gt;

&lt;p&gt;Note that if the GC was not collecting at regular intervals during the test, we would have a build up of 400 million objects (100 million strings in Foo1, another 100 million in Foo2, which also needs 100 million closures and 100 million delegates). The overhead on an object is 8 bytes (two pointers used by the CLR), so that’s approximately 3 GB of memory requirement even without considering the actual data stored in the objects. So the GC clearly is cleaning up old objects during the test, or else it wouldn’t finish successfully.&lt;/p&gt;

&lt;p&gt;So the GC heap is so fast that in a real program, even in tight loops, you can use closures and delegates without even giving it a second’s thought (or even a few nanosecond’s thought). As always, work on a clean, safe design, then profile to find out where the overhead is.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-8259948088152602835?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/8259948088152602835/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=8259948088152602835' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/8259948088152602835'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/8259948088152602835'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/03/amazing-speed-of-net-garbage-collector.html' title='The Amazing Speed of the .NET Garbage Collector'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-1170247403309192221</id><published>2009-02-26T22:42:00.002Z</published><updated>2011-02-04T11:14:53.952Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambdas'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='yield return'/><title type='text'>Making Lambdas and Iterators Play Nicely Together</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/02/26/making-lambdas-and-iterators-play-nicely-together/'&lt;/script&gt;

&lt;p&gt;The major problem with &lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2009/02/functional-replacement-for-using.html"&gt;this idea&lt;/a&gt; is in my favourite feature of C#. In an iterator (a function containing the &lt;strong&gt;yield&lt;/strong&gt; keyword), the code is transformed into a state machine represented by a class. It has to be chopped up into sections, so the function can be &amp;#8220;paused&amp;#8221; after each &lt;strong&gt;yield return&lt;/strong&gt;. Those pieces must all be in the same function, so sadly lambdas don&amp;#8217;t play well with iterators.&lt;/p&gt;  &lt;p&gt;There are a couple of possible future language features which would completely solve this, however. &lt;/p&gt;  &lt;p&gt;Firstly, how about &lt;strong&gt;yield foreach&lt;/strong&gt;. This would take an &lt;strong&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/strong&gt; and yield all the items of it. It would remove the need to write an explicit &lt;strong&gt;foreach&lt;/strong&gt; loop to return a nested sequence. &lt;a href="http://citeseer.ist.psu.edu/cache/papers/cs2/355/http:zSzzSzwww.cs.kuleuven.ac.bezSz~frankzSzPAPERSzSzFTfJP2005.pdf/iterators-revisited-proof-rules.pdf"&gt;This amazing paper&lt;/a&gt; shows how this feature would be implemented (they even picked the same keyword), although the use-case there is to support recursion with good performance.&lt;/p&gt;  &lt;p&gt;Secondly, I&amp;#8217;d like to be able to write an anonymous iterator. This would be a matter of using &lt;strong&gt;yield return&lt;/strong&gt; in the middle of a lambda, and hey presto, the compiler would build me an iterator instead of a normal anonymous method.&lt;/p&gt;  &lt;p&gt;How would these two features help here? Suppose I wanted to use my &lt;strong&gt;&lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2009/02/displaying-nested-evaluation-tree-from.html"&gt;TraceWriter&lt;/a&gt;&lt;/strong&gt; (see the source download) class in an iterator. Here&amp;#8217;s how it would look:&lt;/p&gt;  &lt;div&gt;   &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;IEnumerable&amp;lt;int&amp;gt; MyIterator(TraceWriter w)
{
    &lt;font color="#0000ff"&gt;yield &lt;/font&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 1;
    w.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Not indented yet&amp;quot;&lt;/span&gt;);

    &lt;font color="#0000ff"&gt;yield foreach&lt;/font&gt; w.Indented(() =&amp;gt;
    {
        &lt;font color="#0000ff"&gt;yield &lt;/font&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 2;
        w.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Indented now&amp;quot;&lt;/span&gt;);
        &lt;font color="#0000ff"&gt;yield &lt;/font&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 3;
    });

    w.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Un-indented again&amp;quot;&lt;/span&gt;);
    &lt;font color="#0000ff"&gt;yield &lt;/font&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 4;
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;So we have the same readability as before. This would require a special implementation of the &lt;strong&gt;Indented&lt;/strong&gt; method, specifically for iterators:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; Indented&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; sequence)
{
    WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;{&amp;quot;&lt;/span&gt;);
    _indent++;

    &lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; sequence;

    _indent--;
    WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;}&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;It&amp;#8217;s handy, that &lt;strong&gt;yield foreach&lt;/strong&gt; thing, isn&amp;#8217;t it?&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-1170247403309192221?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/1170247403309192221/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=1170247403309192221' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/1170247403309192221'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/1170247403309192221'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/02/making-lambdas-and-iterators-play.html' title='Making Lambdas and Iterators Play Nicely Together'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-413538867765351570</id><published>2009-02-26T21:14:00.002Z</published><updated>2011-02-04T11:16:56.939Z</updated><title type='text'>Fatal Exceptions, and Why VB.NET Has a Purpose!</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/02/26/fatal-exceptions-and-why-vb-net-has-a-purpose/'&lt;/script&gt;
&lt;p&gt;There&amp;#8217;s a feature in the CLR that is exposed in VB.NET and not in C#. Apparently this is a deliberate decision made by the C# team, which so far they&amp;#8217;ve stuck to. Unfortunately, it&amp;#8217;s a pretty important feature.&lt;/p&gt;  &lt;p&gt;I was prompted by Andrew Pardoe of the CLR team to look more closely at this when considering &lt;code&gt;try&lt;/code&gt;/&lt;code&gt;finally&lt;/code&gt; and the problem of &amp;#8220;fatal&amp;#8221; exceptions. By fatal, I mean an exception that you have no idea how to handle. A good example is &lt;code&gt;NullReferenceException&lt;/code&gt;, which almost certainly indicates a bug. If there&amp;#8217;s a bug, your program is in an unknown state, and you need to capture that state exactly as it is. Ideally the program would terminate at that point. In the interests of flexibility, the CLR does allow you to catch such exceptions. (Then the CLR team tells you that you shouldn&amp;#8217;t &amp;#8211; it&amp;#8217;s a &amp;#8220;fruit of the tree of knowledge&amp;#8221; type of situation.)&lt;/p&gt;  &lt;p&gt;Very often a method will throw a variety of exceptions to indicate that it was unable to finish what it was supposed to do, but it ain&amp;#8217;t the end of the world. These are recoverable exceptions. A simple example is &lt;code&gt;FileInfo.Delete&lt;/code&gt;:&lt;/p&gt;  &lt;div&gt;   &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; errorMessage = &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;;

&lt;span style="color: #0000ff"&gt;try&lt;/span&gt;
{
    &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; FileInfo(&lt;span style="color: #006080"&gt;@&amp;quot;c:\myfile.txt&amp;quot;&lt;/span&gt;).Delete();
}
&lt;span style="color: #0000ff"&gt;catch&lt;/span&gt; (SecurityException x)
{
    errorMessage = x.Message;
}
&lt;span style="color: #0000ff"&gt;catch&lt;/span&gt; (IOException x)
{
    errorMessage = x.Message;
}
&lt;span style="color: #0000ff"&gt;catch&lt;/span&gt; (UnauthorizedAccessException x)
{
    errorMessage = x.Message;
}

&lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (errorMessage != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)
    MessageBox.Show(&lt;span style="color: #006080"&gt;&amp;quot;You idiot - &amp;quot;&lt;/span&gt; + errorMessage);&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Now, there&amp;#8217;s a slight problem, which we&amp;#8217;ll gloss over &amp;#8211; how do you know what exceptions a method will throw? Ultimately, you need accurate, reliable, up-to-date documentation for every method. But instead of waiting for hell to freeze over, let&amp;#8217;s move on.&lt;/p&gt;

&lt;p&gt;When you have an operation that performs many such calls to various APIs, 3rd party libraries and so on, the ideal place to put the handler is at the outermost layer where you can recover. For example, the user presses the button and you run a lot of code to do what the user has asked. The best place to put the &lt;code&gt;try&lt;/code&gt;/&lt;code&gt;catch&lt;/code&gt; is around that whole sequence of operations, so that the &lt;code&gt;catch&lt;/code&gt; can display the error to the user, and so they can figure out why they&amp;#8217;re such an idiot. Inside that operation, you need to use &lt;code&gt;try&lt;/code&gt;/&lt;code&gt;finally&lt;/code&gt; (and related constructs) to ensure that any half-finished stuff is always properly undone. Nice and simple.&lt;/p&gt;

&lt;p&gt;Except for one slight irritation: now the set of exceptions you need to catch is the union of all the recoverable exceptions that might be thrown by all the operations performed within that combined operation. This means that your &lt;code&gt;try&lt;/code&gt;/&lt;code&gt;catch&lt;/code&gt; block potentially has a ridiculously long list of types. It&amp;#8217;s also very easy to miss an exception type here or there, which would mean that your program would crash when it didn&amp;#8217;t need to. Whenever someone performs maintenance on the big operation (or any of the APIs or 3rd party libraries it calls on to), the huge list of &lt;code&gt;catch&lt;/code&gt; blocks needs to be updated to ensure nothing is missed.&lt;/p&gt;

&lt;p&gt;Also this all needs to be done separately for every &lt;code&gt;try&lt;/code&gt;/&lt;code&gt;catch&lt;/code&gt; statement. So you might think of reducing this hideous boilerplate repetition by writing it once:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; Recover(Action action, Action&amp;lt;Exception&amp;gt; recover)
{
    &lt;span style="color: #0000ff"&gt;try&lt;/span&gt;
    {
        action();
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;true&lt;/span&gt;;
    }
    &lt;span style="color: #0000ff"&gt;catch&lt;/span&gt; (SecurityException x)
    {
        recover(x);
    }
    &lt;span style="color: #0000ff"&gt;catch&lt;/span&gt; (IOException x)
    {
        recover(x);
    }
    &lt;span style="color: #0000ff"&gt;catch&lt;/span&gt; (UnauthorizedAccessException x)
    {
        recover(x);
    }
    &lt;span style="color: #008000"&gt;//others...&lt;/span&gt;

    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;false&lt;/span&gt;;
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;You can now write nice neat lambdas to provide the code for the action to try and the single recovery handler. But you still have the same major problem: this long list of all the recoverable exceptions has to include every single one that might be thrown anywhere in any operation.&lt;/p&gt;

&lt;p&gt;What if your product is extensible, such that 3rd parties can write plug-ins for it? How do they add their own recoverable exceptions to the Recover function? They simply can&amp;#8217;t. And even if they could, what if they don&amp;#8217;t remember to? How does your application protect itself?&lt;/p&gt;

&lt;p&gt;So you have explosive complexity and apparently no way to control it.&lt;/p&gt;

&lt;p&gt;At this point, the following quite reasonable thought occurs to you: surely the number of fatal exceptions is smaller than the number of non-fatal ones. Indeed, the number of non-fatal ones is constantly growing as we create new exception classes of our own. Also, if I make any mistakes in constructing my software, I&amp;#8217;d prefer to not crash rather than crash.&lt;/p&gt;

&lt;p&gt;The natural conclusion, which therefore naturally occurs to everyone eventually, is to do this:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;try&lt;/span&gt;
{
    &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; FileInfo(&lt;span style="color: #006080"&gt;@&amp;quot;c:\myfile.txt&amp;quot;&lt;/span&gt;).Delete();
}
&lt;span style="color: #0000ff"&gt;catch&lt;/span&gt; (Exception x)
{
    MessageBox.Show(&lt;span style="color: #006080"&gt;&amp;quot;Couldn't delete file: &amp;quot;&lt;/span&gt; + x.Message);
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;But then you remember that there&amp;#8217;s such a thing as a fatal exception. Although you&amp;#8217;d generally prefer your software not to crash, in the event of a definite bug, it is better for it to crash &amp;#8211; that way, you get an accurate snapshot of the program&amp;#8217;s state. So you need to examine the exception object before you try to handle it:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;try&lt;/span&gt;
{
    &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; FileInfo(&lt;span style="color: #006080"&gt;@&amp;quot;c:\myfile.txt&amp;quot;&lt;/span&gt;).Delete();
}
&lt;span style="color: #0000ff"&gt;catch&lt;/span&gt; (Exception x)
{
    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (!ExceptionPolicy.IsExceptionRecoverable(x))
        &lt;span style="color: #0000ff"&gt;throw&lt;/span&gt;;

    MessageBox.Show(&lt;span style="color: #006080"&gt;&amp;quot;Couldn't delete file: &amp;quot;&lt;/span&gt; + x.Message);
}
    &lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Of course, that &lt;code&gt;IsExceptionRecoverable&lt;/code&gt; method has to be written by you, but only once, and it probably has a relatively short list of exception types to look out for, and that list doesn&amp;#8217;t grow so fast as the list of recoverable exceptions. &lt;/p&gt;

&lt;p&gt;The above solution represents the state of the art according to the &lt;a href="http://msdn.microsoft.com/en-us/library/cc467894.aspx"&gt;Microsoft Enterprise Library&lt;/a&gt;. Unfortunately, it&amp;#8217;s still not right. The problem is to do with the thing I mentioned above about how to correctly write the code within each long and complex operation:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Inside that operation, you need to use &lt;code&gt;try&lt;/code&gt;/&lt;code&gt;finally&lt;/code&gt; (and related constructs) to ensure that any half-finished stuff is always properly undone.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The problem is, you only want the &lt;code&gt;finally&lt;/code&gt; blocks to run for recoverable exceptions, not fatal ones. To repeat what I said right at the start:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;If there&amp;#8217;s a bug, your program is in an unknown state, and you need to capture that state exactly as it is.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So you definitely don&amp;#8217;t want to run any &lt;code&gt;finally&lt;/code&gt; blocks before that state is captured. They might modify it (in fact, that&amp;#8217;s the whole point of them). They might make it worse, cause further corruption, or even throw another exception and so hide the original bug.&lt;/p&gt;

&lt;p&gt;My first thought when this occurred to me was that &lt;code&gt;try&lt;/code&gt;/&lt;code&gt;finally&lt;/code&gt; presents a serious problem. How can we make it execute the &lt;code&gt;finally&lt;/code&gt; block for a recoverable exception but not for a fatal exception?&lt;/p&gt;

&lt;p&gt;Well, we can, sort of. If you don&amp;#8217;t ever catch an exception, the &lt;code&gt;finally&lt;/code&gt; blocks never run. When an exception is thrown, the CLR does not immediately run the &lt;code&gt;finally&lt;/code&gt; blocks. First, it checks to see if there is a suitable &lt;code&gt;catch&lt;/code&gt; in the stack for the current exception. If there is, and only if there is, it runs the enclosed &lt;code&gt;finally&lt;/code&gt; blocks, and then runs the &lt;code&gt;catch&lt;/code&gt; block.&lt;/p&gt;

&lt;p&gt;This is why the correct advice is to never catch fatal exceptions, because merely catching them will trigger the silent execution of &lt;code&gt;finally&lt;/code&gt; blocks when the program is already in an unrecoverable situation.&lt;/p&gt;

&lt;p&gt;But this is sadly no good to us, because we&amp;#8217;ve already established that explicitly catching only the recoverable exception types will lead us to a situation of hideously and unmanageable complexity, and programs that crash when they don&amp;#8217;t need to. It&amp;#8217;s just not practical to work that way.&lt;/p&gt;

&lt;p&gt;The problem all stems from the fact that &lt;code&gt;catch&lt;/code&gt; blocks can only decide to run based on the type of the exception, and this has to be an &amp;#8220;opt in&amp;#8221;. It can&amp;#8217;t be coded the other way round, as an &amp;#8220;opt out&amp;#8221;. Yes, exceptions can be arranged in hierarchies and so that one &lt;code&gt;catch&lt;/code&gt; block can catch all exception types derived from some base class, but this turns out to be useless because there&amp;#8217;s no base class that all recoverable exceptions have in common, except for the class which is also the base class of all fatal exceptions as well.&lt;/p&gt;

&lt;p&gt;So we cry: if only the CLR allowed us to run some code of our own to decide whether to catch an exception, &lt;em&gt;before the finally blocks run&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The surprising answer (to a C# programmer) is that the CLR &lt;em&gt;does &lt;/em&gt;allow us to do that. It just isn&amp;#8217;t made available in C#. Only in VB.NET. Devastating, huh?&lt;/p&gt;

&lt;p&gt;So to do exception handling in C#, in a way that is actually manageable, but also doesn&amp;#8217;t execute code after a fatal exception, you first have to crank up VB.NET and create a class library containing this class:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;Imports&lt;/span&gt; System

&lt;span style="color: #0000ff"&gt;Public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;Class&lt;/span&gt; Exceptions
    &lt;span style="color: #0000ff"&gt;Public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;Shared&lt;/span&gt; &lt;span style="color: #0000ff"&gt;Sub&lt;/span&gt; TryFilterCatch(&lt;span style="color: #0000ff"&gt;ByVal&lt;/span&gt; tryAction &lt;span style="color: #0000ff"&gt;As&lt;/span&gt; Action, _
            &lt;span style="color: #0000ff"&gt;ByVal&lt;/span&gt; filter &lt;span style="color: #0000ff"&gt;As&lt;/span&gt; Func(Of Exception, &lt;span style="color: #0000ff"&gt;Boolean&lt;/span&gt;), _
            &lt;span style="color: #0000ff"&gt;ByVal&lt;/span&gt; handler &lt;span style="color: #0000ff"&gt;As&lt;/span&gt; Action(Of Exception))
        &lt;span style="color: #0000ff"&gt;Try&lt;/span&gt;
            tryAction()
        &lt;span style="color: #0000ff"&gt;Catch&lt;/span&gt; ex &lt;span style="color: #0000ff"&gt;As&lt;/span&gt; Exception &lt;span style="color: #0000ff"&gt;When&lt;/span&gt; filter(ex)
            handler(ex)
        &lt;span style="color: #0000ff"&gt;End&lt;/span&gt; &lt;span style="color: #0000ff"&gt;Try&lt;/span&gt;
    &lt;span style="color: #0000ff"&gt;End&lt;/span&gt; &lt;span style="color: #0000ff"&gt;Sub&lt;/span&gt;
&lt;span style="color: #0000ff"&gt;End&lt;/span&gt; &lt;span style="color: #0000ff"&gt;Class&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This effectively turns the magic feature of VB.NET &amp;#8211; the &lt;code&gt;When&lt;/code&gt; clause that appears next to the &lt;code&gt;Catch&lt;/code&gt; &amp;#8211; into something we can reuse in any CLR-based language. Having built that, you can now go back to C#&amp;#8230; phew!&lt;/p&gt;

&lt;p&gt;Now, supposing you still have that &lt;code&gt;IsExceptionRecoverable&lt;/code&gt; method handy, you can do this:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;Exceptions.TryFilterCatch(() =&amp;gt;
{
    &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; FileInfo(@&lt;span style="color: #006080"&gt;&amp;quot;c:\myfile.txt&amp;quot;&lt;/span&gt;).Delete();
},
ExceptionPolicy.IsExceptionRecoverable, x =&amp;gt;
{
    MessageBox.Show(&lt;span style="color: #006080"&gt;&amp;quot;Couldn't delete file: &amp;quot;&lt;/span&gt; + x.Message);
});&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Given that we are effectively forced to this conclusion by the above reasoning process, it&amp;#8217;s very strange to look at where we&amp;#8217;ve ended up. Essentially, if you want a manageable, fault-tolerant, practical approach to exception handling, the above example is what you need to use, instead of using C# &lt;code&gt;try&lt;/code&gt;/&lt;code&gt;catch&lt;/code&gt; statements.&lt;/p&gt;

&lt;p&gt;How does this situation persist? Why isn&amp;#8217;t general exception filtering exposed in C#, as it is in VB.NET? These are very good questions. It seems that the C# team doesn&amp;#8217;t accept the line of reasoning I gave above. According to them, we should all write long and unmanageable lists of &lt;code&gt;catch&lt;/code&gt; handlers, explicitly listing the recoverable exceptions, based on the apparently trustworthy documentation of every software component we ever call into.&lt;/p&gt;

&lt;p&gt;The CLR team, on the other hand, is well aware of this problem, and is aware that people are forced to try an alternative, and so inevitably make their way down the chain of reasoning I&amp;#8217;ve described here, and the Microsoft Enterprise Library is probably representative of where most people stop in that chain.&lt;/p&gt;

&lt;p&gt;The &lt;a href="http://blogs.msdn.com/cbrumme/archive/2003/10/01/51524.aspx"&gt;earliest reference I&amp;#8217;ve found for all this stuff is here&lt;/a&gt;. It covers all the technical details, and mentions the idea of exposing VB.NET&amp;#8217;s filtering capability.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/clrteam/archive/2009/02/05/catch-rethrow-and-filters-why-you-should-care.aspx"&gt;This is the blog post that Andrew Pardoe pointed me to&lt;/a&gt;. The more I think about it, the more I think it&amp;#8217;s a message to the C# team, rather than to users. The chances of many users hearing the message is low, and the chances of them understanding the implications is probably a little lower still. They must be hoping that the C# team will hear it and understand it. I guess C# is a customer of CLR, so the C# team is &amp;#8220;always right&amp;#8221; in that relationship. Consequently the message will need to come from customers of the C# team!&lt;/p&gt;

&lt;p&gt;In the meantime, the CLR team is doing something about this problem:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419661.aspx"&gt;In version 4 of the CLR, the product team is making exceptions that indicate a corrupted process state distinct from all other exceptions.&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is only part of the solution, of course, because in some situations our own exception types can indicate that the program is in an invalid state. The &amp;#8220;corruption&amp;#8221; is not of the low-level, random byte trashing kind, but it is corruption by a bug, nonetheless. So we need the recoverability criterion to be specified in a customizable way for each &lt;code&gt;try&lt;/code&gt;/&lt;code&gt;catch&lt;/code&gt; situation.&lt;/p&gt;

&lt;p&gt;This means that, even after version 4 of the CLR, we will still need that snippet of VB code. Until the C# team &lt;code&gt;catch&lt;/code&gt;-es up with the VB.NET team.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-413538867765351570?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/413538867765351570/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=413538867765351570' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/413538867765351570'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/413538867765351570'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/02/fatal-exceptions-and-why-vbnet-has.html' title='Fatal Exceptions, and Why VB.NET Has a Purpose!'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-266979849472004294</id><published>2009-02-25T10:08:00.003Z</published><updated>2011-02-04T11:18:17.893Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='dynamic'/><category scheme='http://www.blogger.com/atom/ns#' term='C# 4.0'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>What's Wrong With C# 4.0's dynamic Keyword, and How I Think It Should Be Fixed</title><content type='html'>&lt;p&gt;&lt;b&gt;Update:&lt;/b&gt; Exactly what I want, &lt;a href="http://bartdesmet.net/blogs/bart/archive/2008/11/10/introducing-the-c-ducktaper-bridging-the-dynamic-world-with-the-static-world.aspx"&gt;already implemented, complete with caching of the call site&lt;/a&gt;. Also, Microsoft's Mads Torgersen &lt;a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=417826"&gt;responds to this suggestion here&lt;/a&gt;.

&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/02/25/whats-wrong-with-c-4-0s-dynamic-keyword-and-how-i-think-it-should-be-fixed/'&lt;/script&gt;

&lt;p&gt;C# 4.0 proposes to add the &lt;strong&gt;dynamic&lt;/strong&gt; keyword to the language. There are a few problems with it:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Beginners have no clue what the difference is between &lt;strong&gt;object&lt;/strong&gt;, &lt;strong&gt;var&lt;/strong&gt; and &lt;strong&gt;dynamic&lt;/strong&gt;. This is a relatively minor problem compared to the others, but it's worth considering.&lt;/li&gt;    &lt;li&gt;The dependency of a program on specific features of a dynamic object are not captured in a central definition, defeating the type system. I'll explain this a bit better below.&lt;/li&gt;    &lt;li&gt;There's no intellisense support (this is really the same thing as point 2, but it's so important that it's worth highlighting on its own).&lt;/li&gt;    &lt;li&gt;New language features are an unnecessary pain if you can meet the same need with a library feature - and I believe you can do a &lt;em&gt;better &lt;/em&gt;job with a library feature in this case.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;In a nutshell, I sincerely hope that &lt;strong&gt;dynamic&lt;/strong&gt; is removed from C# 4.0. In its place, there should be a static class in a namespace &lt;strong&gt;System.Dynamic&lt;/strong&gt;. It would have one method, an extension on &lt;strong&gt;object&lt;/strong&gt;:&lt;/p&gt;  &lt;div&gt;   &lt;pre    style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px;  border-top-style: none;   border-left-style: none; overflow: visible; padding-top: 0pxfont-family:consolas, 'Courier New', courier, monospace;font-size:8pt;color:black;"&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;static&lt;/span&gt; TInterface AsDynamic&amp;lt;TInterface&amp;gt;(&lt;span style="color:#0000ff;"&gt;this&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;object&lt;/span&gt; obj)
      where TInterface : class&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This would take any object at all and return a dynamic wrapper that implements the specified interface by forwarding calls onto the wrapped object. The wrinkle here is that &lt;strong&gt;TInterface&lt;/strong&gt; really should be an interface but there's no way of constraining to that (now there's a language feature I'd accept quite happily).&lt;/p&gt;

&lt;p&gt;Now in order to make use of a dynamic object (that is, an object whose type is unknown to me) I simply declare the features I require of that object, in an ordinary interface. Whenever I receive such an object, I wrap it with that interface as soon as possible, and use that interface to refer to it thereafter.&lt;/p&gt;

&lt;p&gt;What's so great about this? Suppose my dynamic object is a frog. So first I declare an interface &lt;strong&gt;IFrog&lt;/strong&gt;:&lt;/p&gt;

&lt;div&gt;
 &lt;pre    style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px;  border-top-style: none;   border-left-style: none; overflow: visible; padding-top: 0pxfont-family:consolas, 'Courier New', courier, monospace;font-size:8pt;color:black;"&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;interface&lt;/span&gt; IFrog
{
   &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; Ribbit();
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This states in a single location what features a dynamic frog must have.&lt;/p&gt;

&lt;p&gt;Now I can make the majority of my code use this interface to refer to frogs. At the "dynamic boundary" where I receive weird objects from the outside world, I immediately convert them to &lt;strong&gt;IFrog&lt;/strong&gt; so the rest of my code can use them:&lt;/p&gt;

&lt;div&gt;
 &lt;pre face="consolas, 'Courier New', courier, monospace" size="8pt" color="black" style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px;  border-top-style: none;   border-left-style: none; overflow: visible; padding-top: 0px"&gt;IFrog f = something.AsDynamic&amp;lt;IFrog&amp;gt;();&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This doesn't change the dynamic nature of what is happening. Exactly the same kind of method resolution now has to happen at runtime, and no capability has been lost compared to the present &lt;strong&gt;dynamic&lt;/strong&gt; keyword design.&lt;/p&gt;

&lt;p&gt;But there are big advantages. Firstly, users don't need to understand a new keyword that clashes conceptually with two other things. Secondly, what if the dynamic system that passes me frogs changes the way it works, so now it expects an argument to be passed to &lt;strong&gt;Ribbit&lt;/strong&gt;? No problem for me. I just update my interface:&lt;/p&gt;

&lt;div&gt;
 &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, 'Courier New', courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color:#0000ff;"&gt;public&lt;/span&gt; &lt;span style="color:#0000ff;"&gt;interface&lt;/span&gt; IFrog
{
   &lt;span style="color:#0000ff;"&gt;void&lt;/span&gt; Ribbit(&lt;span style="color:#0000ff;"&gt;bool&lt;/span&gt; loudly);
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Now when I recompile, the C# compiler will find all the places in my code where I need to provide the new argument. The lesson here is that all languages (whether statically or dynamically typed) end up having these kinds of contracts or dependencies on the features of objects. The advantage of static languages is that it pays to declare those contracts centrally, so you can update them more easily.&lt;/p&gt;

&lt;p&gt;Then there's the intellisense - obviously this works as usual with IFrog. It doesn't work at all with the current C# 4.0 design.&lt;/p&gt;

&lt;p&gt;Finally, this would be a library feature. It would be available in a consistent way from C#, VB, F#, Eiffel, and so on. It's also very optional - if you don't want to see the &lt;strong&gt;AsDynamic&lt;/strong&gt; extension appearing on every class, then don't add using &lt;strong&gt;System.Dynamic&lt;/strong&gt; to your source file.&lt;/p&gt;

&lt;p&gt;Also I may as well point out that it would be easy to instantly find all uses of dynamic type conversion within a solution, by simply finding all references to the &lt;strong&gt;AsDynamic&lt;/strong&gt; method. So no need for a new IDE feature there.&lt;/p&gt;

&lt;p&gt;This solution contains the dynamic stuff rather than spreading it around. It strikes me as being far more in the spirit of C# as a statically typed language designed for large-scale development. Yes, the &lt;strong&gt;dynamic&lt;/strong&gt; keyword makes short examples look cool on the page. But it doesn't make them fun to write in the first place (no intellisense), or to maintain (no central type definition).&lt;/p&gt;

&lt;p&gt;How about it, Microsoft?&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-266979849472004294?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/266979849472004294/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=266979849472004294' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/266979849472004294'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/266979849472004294'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/02/what-wrong-with-c-40-dynamic-keyword.html' title='What&amp;#39;s Wrong With C# 4.0&amp;#39;s dynamic Keyword, and How I Think It Should Be Fixed'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-1795195354728745647</id><published>2009-02-13T20:47:00.002Z</published><updated>2011-02-04T11:17:43.990Z</updated><title type='text'>General Theory of Resources</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/02/13/general-theory-of-resources/'&lt;/script&gt;

&lt;p&gt;Having blogged the other day about a &lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2009/02/functional-replacement-for-using.html"&gt;different way of doing automatic cleanup&lt;/a&gt;, I&amp;#8217;ve been mulling it over and also &lt;a href="http://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface/538590#538590"&gt;answering a question on StackOverflow&lt;/a&gt;, and decided that I need to assemble a taxonomy of resources; what kinds there are, how to recognise them by their distinctive markings, guidelines for upkeep, training, feeding, breeding, etc. And because I&amp;#8217;m obsessive-compulsive, I also wanted to develop a complete and rigorous theory of resources from the ground up.&lt;/p&gt;  &lt;p&gt;I don&amp;#8217;t like it when I have to say &amp;#8220;In that &lt;em&gt;sort of&lt;/em&gt; situation I normally &lt;em&gt;try something&lt;/em&gt; like this and it &lt;em&gt;usually seems&lt;/em&gt; to work.&amp;#8221;&lt;/p&gt;  &lt;p&gt;So without further ado, I present the &lt;em&gt;General Theory of Resources&lt;/em&gt;.&lt;/p&gt;  &lt;h3&gt;Resources Modeled by Conceptual Bits&lt;/h3&gt;  &lt;p&gt;Imagine an array of bits, ones and zeros. Each represents something that has to be rationed between the parts of your program that want to use it. Only one &amp;#8220;user&amp;#8221; at a time can take ownership of the thing represented by the bit. When the thing is in use, its corresponding bit is set to 1. Otherwise, it is set to 0. If all the bits are 1 when you show up with your begging bowl, you&amp;#8217;re out of luck. Note that these are just conceptual bits; real implementations might not actually maintain an array of bits or Booleans specifically for this purpose. But the two-state nature is always there nonetheless. We can imagine each available resource being modeled by a bit indicating whether it is currently reserved for exclusive use.&lt;/p&gt;  &lt;p&gt;Are we talking about an infinite number of bits? Of course not. If we were, then we wouldn&amp;#8217;t need to go any further in this discussion. We are frequently talking about a &lt;em&gt;single&lt;/em&gt; bit. Often we are talking about a number of bits just large enough to fool us into thinking that our program is correct, only to find out later that it isn&amp;#8217;t because it eventually runs out of bits.&lt;/p&gt;  &lt;h3&gt;Enter and Exit&lt;/h3&gt;  &lt;p&gt;Atop this set of bits, there is a pair of operations, which I&amp;#8217;ll call &lt;strong&gt;Enter&lt;/strong&gt; and &lt;strong&gt;Exit&lt;/strong&gt;. When &lt;strong&gt;Enter&lt;/strong&gt; executes, it sets a bit, or possibly a bunch of bits to 1. When &lt;strong&gt;Exit&lt;/strong&gt; executes, it sets the bits back to 0 again. The two operations abstract over the underlying set of bits.&lt;/p&gt;  &lt;p&gt;We sometimes say that a resource &amp;#8220;exists&amp;#8221; whenever we have executed &lt;strong&gt;Enter&lt;/strong&gt; but have not yet executed &lt;strong&gt;Exit&lt;/strong&gt; in the right way to reverse the state changes caused by &lt;strong&gt;Enter&lt;/strong&gt;. A correct program must execute &lt;strong&gt;Exit&lt;/strong&gt; once for every time it executes &lt;strong&gt;Enter&lt;/strong&gt;.&lt;/p&gt;  &lt;h3&gt;Fungibility&lt;/h3&gt;  &lt;p&gt;You don&amp;#8217;t complain to the bank if they give you &amp;#8220;someone else&amp;#8217;s cash&amp;#8221;; it can be any old cash, as long as it adds up to the required value.&lt;/p&gt;  &lt;p&gt;Some resources are &lt;em&gt;fungible&lt;/em&gt;, meaning that the caller doesn&amp;#8217;t care which particular bunch of bits is set to 1. An incorrect program would run out of such fungible bits because it would forget to &lt;strong&gt;Exit&lt;/strong&gt; and so the number of 1-bits would build up over time, until eventually there would be no 0-bits remaining.&lt;/p&gt;  &lt;p&gt;If you came home after leaving your kids with the babysitter, and found that they were different kids, you wouldn&amp;#8217;t be satisfied if the baby sitter said, &amp;#8220;They look pretty similar to your kids, don&amp;#8217;t they?&amp;#8221;&lt;/p&gt;  &lt;p&gt;Other resources are non-fungible, meaning that the caller requests that a specific bit must be set, so each bit has a meaningful identity. An incorrect program would try to set a non-fungible bit to 1 that it had already set to 1. Sometimes a resource has only one bit to play with, in which case it is surely non-fungible, because we cannot use it without implicitly specifying which bit we want to use.&lt;/p&gt;  &lt;h3&gt;Orthogonality&lt;/h3&gt;  &lt;p&gt;Some resource types are &lt;em&gt;orthogonal&lt;/em&gt;, meaning that the states of the bits are effectively mutually independent (they may be bunched together by the &lt;strong&gt;Enter&lt;/strong&gt; and &lt;strong&gt;Exit&lt;/strong&gt; operations, but if those bunches are mutually orthogonal then we still say that the resource is orthogonal).&lt;/p&gt;  &lt;p&gt;Some are non-orthogonal, meaning that the states of the bits are entangled in some way, even though they are manipulated by separate &lt;strong&gt;Enter&lt;/strong&gt; and &lt;strong&gt;Exit&lt;/strong&gt; operations. Sometimes a resource has only one bit to play with, in which case we may as well call it orthogonal (because there is nothing for the single bit to be entangled with).&lt;/p&gt;  &lt;p&gt;The only non-orthogonal kind of resource I consider here is &lt;em&gt;stack-like&lt;/em&gt;. There may be other useful kinds, but I can&amp;#8217;t think of any off hand.&lt;/p&gt;  &lt;h3&gt;Some Examples&lt;/h3&gt;  &lt;p&gt;Here&amp;#8217;s a nice table of some contrived examples and their various attributes:&lt;/p&gt;  &lt;div style="overflow: scroll"&gt;   &lt;table border="0" cellspacing="8" cellpadding="4" width="900"&gt;&lt;tbody&gt;       &lt;tr&gt;         &lt;td valign="top" width="151"&gt;&lt;strong&gt;&lt;font color="#5172a4"&gt;Resource&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;          &lt;td valign="top" width="174"&gt;&lt;strong&gt;&lt;font color="#5172a4"&gt;Enter&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;          &lt;td valign="top" width="167"&gt;&lt;strong&gt;&lt;font color="#5172a4"&gt;Exit&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;          &lt;td valign="top" width="131"&gt;&lt;strong&gt;&lt;font color="#5172a4"&gt;Bits&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;          &lt;td valign="top" width="123"&gt;&lt;strong&gt;&lt;font color="#5172a4"&gt;Fungible&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;          &lt;td valign="top" width="96"&gt;&lt;strong&gt;&lt;font color="#5172a4"&gt;Orthogonal&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;       &lt;/tr&gt;        &lt;tr&gt;         &lt;td valign="top" width="150"&gt;Unmanaged memory in C&lt;/td&gt;          &lt;td valign="top" width="172"&gt;&lt;strong&gt;malloc&lt;/strong&gt;&lt;/td&gt;          &lt;td valign="top" width="165"&gt;&lt;strong&gt;free&lt;/strong&gt;&lt;/td&gt;          &lt;td valign="top" width="129"&gt;One per word of memory&lt;/td&gt;          &lt;td valign="top" width="122"&gt;Yes&lt;/td&gt;          &lt;td valign="top" width="104"&gt;Yes&lt;/td&gt;       &lt;/tr&gt;        &lt;tr&gt;         &lt;td valign="top" width="150"&gt;A stack of integers&lt;/td&gt;          &lt;td valign="top" width="172"&gt;A &lt;strong&gt;Push&lt;/strong&gt; method&lt;/td&gt;          &lt;td valign="top" width="165"&gt;A &lt;strong&gt;Pop&lt;/strong&gt; method&lt;/td&gt;          &lt;td valign="top" width="129"&gt;One bit per stack depth&lt;/td&gt;          &lt;td valign="top" width="122"&gt;No&lt;/td&gt;          &lt;td valign="top" width="104"&gt;No&lt;/td&gt;       &lt;/tr&gt;        &lt;tr&gt;         &lt;td valign="top" width="149"&gt;A static Boolean flag, &lt;strong&gt;_entered&lt;/strong&gt;, protecting a method from reentrance&lt;/td&gt;          &lt;td valign="top" width="171"&gt;&lt;font face="Courier New"&gt;// start of method              &lt;br /&gt;if (_entered ==               &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; true) return;               &lt;br /&gt;              &lt;br /&gt;_entered = true;&lt;/font&gt;&lt;/td&gt;          &lt;td valign="top" width="164"&gt;&lt;font face="Courier New"&gt;// end of method              &lt;br /&gt;_entered = false;&lt;/font&gt;&lt;/td&gt;          &lt;td valign="top" width="127"&gt;One&lt;/td&gt;          &lt;td valign="top" width="121"&gt;No&lt;/td&gt;          &lt;td valign="top" width="110"&gt;Yes&lt;/td&gt;       &lt;/tr&gt;        &lt;tr&gt;         &lt;td valign="top" width="149"&gt;A file&lt;/td&gt;          &lt;td valign="top" width="171"&gt;The &lt;strong&gt;CreateFile&lt;/strong&gt; API&lt;/td&gt;          &lt;td valign="top" width="164"&gt;The &lt;strong&gt;CloseHandle&lt;/strong&gt; API&lt;/td&gt;          &lt;td valign="top" width="127"&gt;One per file&lt;/td&gt;          &lt;td valign="top" width="121"&gt;No&lt;/td&gt;          &lt;td valign="top" width="110"&gt;Yes&lt;/td&gt;       &lt;/tr&gt;        &lt;tr&gt;         &lt;td valign="top" width="147"&gt;An XML output stream&lt;/td&gt;          &lt;td valign="top" width="170"&gt;A method such as &lt;strong&gt;BeginElement&lt;/strong&gt;&lt;/td&gt;          &lt;td valign="top" width="162"&gt;A method such as &lt;strong&gt;EndElement&lt;/strong&gt;&lt;/td&gt;          &lt;td valign="top" width="126"&gt;One per open element&lt;/td&gt;          &lt;td valign="top" width="120"&gt;No&lt;/td&gt;          &lt;td valign="top" width="117"&gt;No&lt;/td&gt;       &lt;/tr&gt;        &lt;tr&gt;         &lt;td valign="top" width="148"&gt;A thread-local integer, &lt;strong&gt;_entered&lt;/strong&gt;, that monitors recursion into a method&lt;/td&gt;          &lt;td valign="top" width="170"&gt;&lt;font face="Courier New"&gt;// start of method              &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;_entered++;&lt;/font&gt;&lt;/td&gt;          &lt;td valign="top" width="163"&gt;&lt;font face="Courier New"&gt;// end of method              &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;_entered--;&lt;/font&gt;&lt;/td&gt;          &lt;td valign="top" width="127"&gt;One per possible level of recursion&lt;/td&gt;          &lt;td valign="top" width="121"&gt;No&lt;/td&gt;          &lt;td valign="top" width="120"&gt;No&lt;/td&gt;       &lt;/tr&gt;     &lt;/tbody&gt;&lt;/table&gt; &lt;/div&gt;  &lt;p&gt;Something to consider: I give no example that is both fungible &lt;em&gt;and&lt;/em&gt; non-orthogonal. If a resource is non-orthogonal, it means that the user has to be careful about the order in which it takes ownership of or releases ownership instances of that resource. It cannot do this if it is required to treat the resource as fungible, to not care which instance it is holding onto. So non-orthogonal implies non-fungible.&lt;/p&gt;  &lt;p&gt;Another thing that should certainly be clear by now is that a &amp;quot;resource&amp;quot; is not something the operating system provides you with, implemented in native code. It can be, in the case of resources encapsulated in kernel handles that can be closed with &lt;strong&gt;CloseHandle&lt;/strong&gt;, but there are other things, which you can write all by yourself, in pure C# or VB.NET or F#, which are also best thought of as resources.&lt;/p&gt;  &lt;p&gt;Now let&amp;#8217;s pick a few of them apart to make sure it&amp;#8217;s all clear.&lt;/p&gt;  &lt;h3&gt;Unmanaged Memory in C&lt;/h3&gt;  &lt;p&gt;This may seem like a strange example to pick, because we have managed memory these days. But managed memory is fundamentally the same as unmanaged memory except that the runtime performs lazy cleanup automatically on another thread, and the question we must ask is: what makes this an appropriate solution for managing a resource? With what kinds of resource may we use such a clever solution?&lt;/p&gt;  &lt;p&gt;Firstly, consider the C unmanaged memory heap, also known as the &amp;#8220;free store&amp;#8221;. We&amp;#8217;ll assume memory has a resolution of one &amp;#8220;word&amp;#8221; (which would typically be either 4 or 8 bytes, but that doesn&amp;#8217;t matter right now). Each word is either part of the free memory or it is part of some allocated memory. So apart from its actual contents (which we don&amp;#8217;t presently care about at all), each word has one of two states associated with it: 0 for free, or 1 for allocated. These state bits are all completely orthogonal - independent from each other.&lt;/p&gt;  &lt;p&gt;On top of this simple model, the heap provides a convenient abstraction: you can use &lt;strong&gt;Enter&lt;/strong&gt; to find N contiguous free words for you and it will mark them as allocated (set the bit corresponding to each word). Later on, you can pass to &lt;strong&gt;Exit&lt;/strong&gt; the address of the first word you were allocated and the heap will set those words back to the unallocated state (unset the bits). Each bunch of bits is orthogonal with respect to all other bunches, because the bunches can never overlap.&lt;/p&gt;  &lt;p&gt;To reiterate, we are not talking about manipulating the stuff stored in the words (that&amp;#8217;s the application&amp;#8217;s job). We&amp;#8217;re just imagining that the heap keeps track of which words are in use and which are free by recording those facts in a &lt;em&gt;separate&lt;/em&gt; array of bits, one bit for each word of memory in the process. Of course in practice the heap can optimize its data structures so it doesn&amp;#8217;t actually need to keep an array of bits to track the allocation status of every word separately.&lt;/p&gt;  &lt;p&gt;If we rewrite the heap&amp;#8217;s operations in C#, using my names for them, then they look like this:&lt;/p&gt;  &lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;   &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;     &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;IntPtr Enter(&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; wordsToAllocate);&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Exit(IntPtr blockToFree);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This is the standard pattern for an orthogonal resource. The parameter(s) to &lt;strong&gt;Enter&lt;/strong&gt; do not give the identity of the bits that need to be set. Instead, they describe what is needed in a more general sense, and the &lt;strong&gt;Enter&lt;/strong&gt; operation finds a group of bits that fit the bill: any group of bits representing a contiguous region of words of the length requested.&lt;/p&gt;

&lt;p&gt;We then have this token or receipt being returned by &lt;strong&gt;Enter&lt;/strong&gt; and we have to give it back to &lt;strong&gt;Exit&lt;/strong&gt; when we no longer need the memory. The token can be used to access the block of memory, and it also is the key to freeing it.&lt;/p&gt;

&lt;h3&gt;A Stack of Integers&lt;/h3&gt;

&lt;p&gt;Now consider a stack of integers, something like a &lt;strong&gt;Stack&amp;lt;int&amp;gt;&lt;/strong&gt;. The &lt;strong&gt;Enter&lt;/strong&gt; operation takes the thing to put on the stack. This puts the system (the stack) into a state of being taller than it was before. However, the &lt;strong&gt;Exit&lt;/strong&gt; operation does not require any information. It is the nature of a stack to only let you remove the top-most item, so all you need to tell it is that you would like it to remove something. You don&amp;#8217;t have to tell it which item to remove (if you could do that, it wouldn&amp;#8217;t be a stack). If this isn&amp;#8217;t what your program needs, then you shouldn&amp;#8217;t be using a stack.&lt;/p&gt;

&lt;p&gt;As with any other resource manager, a stack has a conceptual array of bits. It is usually very large, but of course not infinite. Most of the bits are set to 0, most of the time. All the bits set to 1 are at the front of the array, and each 1-bit represents an item on the stack. &lt;/p&gt;

&lt;table border="1" cellspacing="0" cellpadding="0" width="301"&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td width="29" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&amp;#8230;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;When we push something on the stack, we set the next 0-bit to 1: &lt;/p&gt;

&lt;table border="1" cellspacing="0" cellpadding="0" width="301"&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td width="29" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;strong&gt;&lt;font color="#d55e2b"&gt;1&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&amp;#8230;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;When we pop something off the stack, we set the last 1-bit to 0:&lt;/p&gt;

&lt;table border="1" cellspacing="0" cellpadding="0" width="301"&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td width="29" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;1&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;strong&gt;&lt;font color="#d55e2b"&gt;0&lt;/font&gt;&lt;/strong&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&lt;font color="#c0c0c0"&gt;0&lt;/font&gt;&lt;/td&gt;

      &lt;td width="30" align="center"&gt;&amp;#8230;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;Obviously there is nothing like orthogonality here. The bits are very much entangled such that no state change can occur that would stop the bits from being properly sorted into two neat groups. You certainly can&amp;#8217;t just flip the state of any bit. Nor is there fungibility, because the identity of a specific bit to modify is implied by the operation we execute (non-orthogonality implies non-fungibility, remember?)&lt;/p&gt;

&lt;p&gt;If we wanted to we could make our stack resource fit the same pattern as the unmanaged heap functions, with a little creativity and shoehorning. Firstly, the &lt;strong&gt;Enter&lt;/strong&gt; operation might return the new height of the stack, which would serve as a unique resource handle. &lt;strong&gt;Exit&lt;/strong&gt; would then accept that same value. Now we&amp;#8217;d have an interface much like the above memory interface. But &lt;strong&gt;Exit&lt;/strong&gt; would have to throw an exception if we passed it a value that was not the current height of the stack. Apart from performing this check, there is no other purpose in passing a value to it. So it is &lt;em&gt;thoroughly misleading&lt;/em&gt; to expose the above interface on a stack-like resource. Instead, stack-like resources should have this kind of interface:&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Enter(T item);&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;T Exit();&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This makes it obvious that there is no choice about which state the stack will be restored to next. Bear in mind that the &lt;strong&gt;item&lt;/strong&gt; parameter is quite optional. As with the memory example, we&amp;#8217;re not interested here in what the job stack is doing, but merely it how it behaves as a resource.&lt;/p&gt;

&lt;h3&gt;A Boolean Flag as a Recursion Guard&lt;/h3&gt;

&lt;p&gt;Sometimes you need to protect a method against re-entrance. For example, suppose you have an event handler that in turn fires another event. There is a danger that someone else will wire up the other event to fire the event your handler is wired up to, and there will be an endless recursion. To protect against this, you can create a static Boolean variable and make your event handler do nothing at all if it is &lt;strong&gt;true&lt;/strong&gt;. Otherwise your event handler is able to run normally. First it sets the flag to &lt;strong&gt;true&lt;/strong&gt;, then it goes about its business (firing the other event), and then sets the flag back to &lt;strong&gt;false&lt;/strong&gt; again. This stops the infinite recursion from happening.&lt;/p&gt;

&lt;p&gt;But it also means that your event handler (or whatever method you apply this approach to) is a resource, albeit a very limited one. It can only be used by one client at a time in the whole process. Consequently it is modeled by a single logical state-bit (indeed, it is implemented by one, in the form of the Boolean variable).&lt;/p&gt;

&lt;p&gt;This definitely makes it non-fungible (because we cannot help but specify which bit we want to take over) but also orthogonal (because there are no other bits for this single bit to be entangled with).&lt;/p&gt;

&lt;h3&gt;File Handles&lt;/h3&gt;

&lt;p&gt;Now for the really complicated example. With file handles, the &lt;strong&gt;Enter&lt;/strong&gt; operation produces a unique identifier that you have to hold on to. You then have to pass the same identifier back to &lt;strong&gt;Exit&lt;/strong&gt; to close the file handle&lt;strong&gt;. &lt;/strong&gt;So far, it looks a lot like memory. But there&amp;#8217;s an added wrinkle, which is that there are two different kinds of resource here: files and handles.&lt;/p&gt;

&lt;p&gt;The OS maintains a set of handles, and that constitutes a system which does indeed have the same properties as the C memory heap. Each possible handle value has an orthogonal Boolean state (allocated, unallocated) associated with it, just as every word of memory does. Applications are not interested in which handle value they receive, making them also fungible.&lt;/p&gt;

&lt;p&gt;But the OS also maintains persistent files with unique names on your hard drive, and these each have an orthogonal state-bit associated with each of them, if we consider write-locking, which is the most problematic case. But these are definitely non-fungible, because they are identified by their names. (Note that if you build an abstraction on top if this system to make up random temporary filenames, then they become fungible again, but that&amp;#8217;s another story.)&lt;/p&gt;

&lt;p&gt;In reality, the &lt;strong&gt;Enter&lt;/strong&gt; operation presented to applications is actually two operations that together form an atomic transaction. First the specified file is locked, meaning that its associated bit is set to 1. Then an unallocated handle is found (which is entirely the choice of the OS, because like money and memory, handle values are fungible) and its bit is also set to 1.&lt;/p&gt;

&lt;p&gt;Consequently, although the &amp;#8220;handle system&amp;#8221; allows multiple simultaneous handles to exist, the file system forces us to treat files very carefully as resources. It is vital to understand this, because the &lt;strong&gt;Enter&lt;/strong&gt;/&lt;strong&gt;Leave&lt;/strong&gt; API looks treacherously similar to the memory API:&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;IntPtr Enter(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; fileName);&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Exit(IntPtr handleToClose);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;It has to look like that because handles work that way. But files do not &amp;#8211; they are closer to the example of using a Boolean flag to guard against reentrance.&lt;/p&gt;

&lt;p&gt;This frequently tricks people into thinking that they can treat file handles in the same way as memory &amp;#8211; that is, let a lazy garbage collector take care of calling &lt;strong&gt;Exit&lt;/strong&gt; automatically some time, hopefully not too long after there are no remaining references to the file handle. But the difference is in the information being passed into &lt;strong&gt;Enter&lt;/strong&gt;. It is not a general description of what might fit the bill, but the specific identity of the one and only thing that is needed.&lt;/p&gt;

&lt;p&gt;So the truth is that a program that fails to close its file handles in a well-understood way is probably not going to work very well. On Windows there is in fact no way of opening a file without locking it against at least one other operation (deletion), so even non-exclusive file handles have some problems.&lt;/p&gt;

&lt;p&gt;As a digression, consider directories or folders in the file system. &lt;strong&gt;Enter&lt;/strong&gt; creates a directory and &lt;strong&gt;Leave&lt;/strong&gt; destroys it. There is one root directory which cannot be destroyed, and all other directories must have a parent directory. The result is a tree-like structure. But we can conceptually simplify it by thinking of it as a set of interleaved stacks. The chain from any leaf directory to the root is a stack, so we know for sure that tree-like resources are at least as restrictive as stack-like resources.&lt;/p&gt;

&lt;p&gt;The other two examples are not appreciably different from what we&amp;#8217;ve already examined. A stream of XML being written sequentially &amp;#8211; however it is implemented &amp;#8211; is effectively a stack. Each 1-bit represents an open element. The elements must be closed in the right order to ensure well-formed XML is produced. And the integer being used to monitor the level of recursion into a method, that too is a stack: one that stores nothing except a record of its current depth.&lt;/p&gt;

&lt;h3&gt;Internal Resources vs External Resources&lt;/h3&gt;

&lt;p&gt;One crucial point that should be clear by now is that there is not really a distinction between states &amp;#8220;inside&amp;#8221; your program and states &amp;#8220;outside&amp;#8221; of it. There is a tendency among C# programmers to think of the stuff they write themselves as &amp;#8220;managed&amp;#8221; (because it&amp;#8217;s in managed code) and the concepts exposed by the operating system as native or &amp;#8220;unmanaged&amp;#8221;.&lt;/p&gt;

&lt;p&gt;In fact, if your program internally maintains state, and the state needs to obey rules like the ones described here, then it inevitably defines resources of its own. And unless you take steps to provide automatic management of the lifetimes of your custom resources, then they are unmanaged resources, no matter what language they are written in or what runtime technology they are based on.&lt;/p&gt;

&lt;p&gt;While an object exists in the CLR, it may have internal mutable state, and there may be rules for the correct use of that state, such that we have to conclude unavoidably that it is a type of resource, and it may or may not be be fungible or orthogonal. So the fact that the whole object will eventually be garbage collected is no comfort. What matters is that the state of it is modified correctly during its lifetime. We need some kind of automatic resource management to deal with the internal state of our own objects, as well as the objects exposed to us the operating system.&lt;/p&gt;

&lt;p&gt;So what does all this tell us? It tells us that managed memory is one kind of resource among many, that the fundamental nature of resources means that they require management of some kind, and that the technique (lazy garbage collection) applicable to management of memory is only applicable because of specific properties of that kind of resource (fungibility, orthogonality). Other resources do not have those properties, and yet still need to be managed. So we need other techniques for them.&lt;/p&gt;

&lt;h3&gt;Resource Management Techniques&lt;/h3&gt;

&lt;p&gt;How can we manage resources easily in C#? By taking advantage of facilities in the language wherever possible. We have the interface to the resource in the form of the &lt;strong&gt;Enter&lt;/strong&gt; and &lt;strong&gt;Exit&lt;/strong&gt; functions, but we would like to avoid the kind of problems that occur when we forget to call &lt;strong&gt;Exit&lt;/strong&gt; once for each call to &lt;strong&gt;Enter&lt;/strong&gt;. So we want something easier than merely putting in the calls manually.&lt;/p&gt;

&lt;p&gt;There are three solutions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Finalizers &lt;/li&gt;

  &lt;li&gt;IDisposable/using &lt;/li&gt;

  &lt;li&gt;Gateways (methods that &lt;strong&gt;Enter&lt;/strong&gt;, forward to a delegate, then &lt;strong&gt;Exit&lt;/strong&gt;) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first two are often confused and conflated.&amp;#160; The last one is, to my mind, massively superior to the other two, for reasons that should become clear, and yet is rarely described in this context as far as I know. I&amp;#8217;ve coined the term &amp;#8220;gateway&amp;#8221; because I&amp;#8217;m not aware of another term for them, so please let me know if there&amp;#8217;s a better name.&lt;/p&gt;

&lt;h3&gt;Finalizers&lt;/h3&gt;

&lt;p&gt;Finalizers are essentially horrid nasty things. It should rarely be necessary to write one. It is notoriously difficult to write one correctly. I have never bothered.&lt;/p&gt;

&lt;p&gt;The basic idea is to hitch a ride with the GC&amp;#8217;s ability to lazily dispose of memory resources. The information needed to &lt;strong&gt;Exit&lt;/strong&gt; a resource is stored in an object, and when that object is reclaimed by the GC, the object&amp;#8217;s finalizer executes and calls &lt;strong&gt;Exit&lt;/strong&gt; for the resource.&lt;/p&gt;

&lt;p&gt;The GC schedules the finalizer to run lazily (that is, some time soon but not immediately or at a predictable time), which means that it is only really useful for resources that are fungible. Consider what this means for file handles: finalization will ensure that your process does not run out of handles, because they are fungible and in plentiful supply, but it does not help at all in avoiding bugs caused by holding onto file locks for longer than necessary, because files are non-fungible.&lt;/p&gt;

&lt;p&gt;And don&amp;#8217;t even consider trying to manage stack-like resources with finalizers. Imagine the mess, with things being popped when they shouldn&amp;#8217;t be.&lt;/p&gt;

&lt;p&gt;The information needed to &lt;strong&gt;Exit&lt;/strong&gt; the resource must be stored in value-type fields only; it is not generally safe to access other reference objects (classes) from a finalizer. This means that finalizers are only really useful for resources defined by the operating system as kernel objects (and in fact there is a better way of encapsulating those, called the &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx"&gt;SafeHandle&lt;/a&gt;.)&lt;/p&gt;

&lt;p&gt;So the less said about finalizers the better.&lt;/p&gt;

&lt;h3&gt;IDisposable/using&lt;/h3&gt;

&lt;p&gt;The other official way of managing resources is to encapsulate the resource in an object (as with the finalizer approach) and to give it a &lt;strong&gt;Dispose&lt;/strong&gt; method, as defined in the interface &lt;strong&gt;IDisposable&lt;/strong&gt;. The construction of the object corresponds to &lt;strong&gt;Enter&lt;/strong&gt;, and &lt;strong&gt;Dispose&lt;/strong&gt; serves as an &lt;strong&gt;Exit&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Then the language provides the &lt;strong&gt;&lt;a href="http://www.jaggersoft.com/csharp_standard/15.13.htm"&gt;using statement&lt;/a&gt;&lt;/strong&gt; as a convenient way of ensuring that &lt;strong&gt;Dispose&lt;/strong&gt; will be called when the flow of control leaves a specified scope:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt; using&lt;/span&gt; ( resource-acquisition ) embedded-statement &lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This approach is fully deterministic and non-lazy. It has none of the limitations of finalizers. Because the &lt;strong&gt;using&lt;/strong&gt; statement weaves itself into the thread&amp;#8217;s method-call stack, it works very well with stack resources - each object&amp;#8217;s &lt;strong&gt;Dispose&lt;/strong&gt; is guaranteed by the C# specification to be called in the reverse order that the objects were constructed, assuming they were constructed in the &lt;em&gt;resource-acquisition&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;There are several intrinsic technical drawbacks, however:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The fact that &lt;strong&gt;Dispose&lt;/strong&gt; is available as a public method gives the impression of an orthogonal resource. You don&amp;#8217;t have to employ the using statement &amp;#8211; you can just call &lt;strong&gt;Dispose&lt;/strong&gt; manually whenever you want. This would play havoc with a stack-like resource just as surely as using a finalizer. &lt;/li&gt;

  &lt;li&gt;It is surprisingly easy to forget to put in the &lt;strong&gt;using&lt;/strong&gt; statement. There are ways to mitigate this, but the problem is that you do have to know that the problem exists before you can take the necessary steps. Implementing a resource as an object does not make it difficult to abuse. It makes it easy to abuse. &lt;/li&gt;

  &lt;li&gt;The &lt;strong&gt;using&lt;/strong&gt; statement ensures that &lt;strong&gt;Dispose&lt;/strong&gt; is called even if an exception propagates from the &lt;em&gt;embedded-statement&lt;/em&gt;. However, little is said about what happens if &lt;strong&gt;Dispose&lt;/strong&gt; then throws another exception. This is all too likely in many common cases. What actually happens is that the CLR discards the first exception, so all information about the original cause is lost. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So the &lt;strong&gt;IDisposable&lt;/strong&gt;/&lt;strong&gt;using&lt;/strong&gt; technique doesn&amp;#8217;t exactly call out to the user to employ it correctly. There are various ways to use it wrongly, and the exception problem is especially irritating. Nevertheless it is possible to use it correctly with a wide range of resources. Because it follows the program stack as it grows and shrinks, it obeys the rules of stack-like resources. Because it is deterministic, it is able to provide the predictable immediate &lt;strong&gt;Exit&lt;/strong&gt; necessary when handling non-fungible resources.&lt;/p&gt;

&lt;h3&gt;The Cultural Problem with IDisposable&lt;/h3&gt;

&lt;p&gt;But these mere technical problems are minor compared with the cultural problem that exists around this technique. These are caused by copious amounts of official or semi-official documentation which confuse it with finalizers, in apparent denial of their different areas of applicability. For example, &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc163392.aspx"&gt;in this article&lt;/a&gt; we are shown the &amp;#8220;basic &lt;strong&gt;IDisposable&lt;/strong&gt; pattern&amp;#8221; and sure enough, it has a finalizer as well. In such articles &lt;strong&gt;IDisposable&lt;/strong&gt; is described as a safety feature to be added to any class that has a finalizer, when in fact it is a general mechanism for hooking into the program stack unwinding process via objects, built on top of the more fundamental &lt;strong&gt;try&lt;/strong&gt;/&lt;strong&gt;finally&lt;/strong&gt; mechanism.&lt;/p&gt;

&lt;p&gt;The logical fallacy that results is like Woody Allen&amp;#8217;s conclusion that &amp;#8220;All men are Socrates&amp;#8221;. The advice, if read carefully, is merely that all finalizable classes should also implement &lt;strong&gt;IDisposable&lt;/strong&gt;. But the idea people frequently come away with is that any class that implements &lt;strong&gt;IDisposable&lt;/strong&gt; should also have a finalizer. They get it completely the wrong way around.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve found it almost impossible to shift this two-way link from many people&amp;#8217;s minds, so much so that it is often controversial to suggest managing a stack-like resource with &lt;strong&gt;IDisposable&lt;/strong&gt;, because some people will insist that the resource must also have a finalizer &amp;#8220;just in case the user forgets to call &lt;strong&gt;Dispose&lt;/strong&gt;&amp;#8221;. Of course, for a stack-like resource the finalizer will be no help at all. In fact it will be no use for any resource defined in terms of reference objects, because it is not safe to manipulate them from a finalizer.&lt;/p&gt;

&lt;p&gt;This cultural problem doesn&amp;#8217;t exist in C++/CLI, because there the existence of &lt;strong&gt;IDisposable&lt;/strong&gt; is hidden behind the C++ language facility called a &lt;em&gt;destructor&lt;/em&gt;. A typical C++/CLI program would have lots of classes that implement &lt;strong&gt;IDisposable&lt;/strong&gt; without the programmer giving it a second thought, and none of them would have finalizers. In C++, destructors are quite often used to manage stack-like resources, which in C++/CLI automatically translates into &lt;strong&gt;IDisposable&lt;/strong&gt; being employed for that same purpose. This is due mostly to Herb Sutter, &lt;a href="http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae"&gt;whose annotations here are particularly illuminating&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Gateways&lt;/h3&gt;

&lt;p&gt;The cultural problems around &lt;strong&gt;IDisposable&lt;/strong&gt; prompted me to look for an alternative, and happily I&amp;#8217;ve found one that is applicable in a lot of cases. I already described it in &lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2009/02/functional-replacement-for-using.html"&gt;a previous blog post&lt;/a&gt;, although there I merely extolled its virtue of being more expressive than the &lt;strong&gt;using&lt;/strong&gt; statement.&lt;/p&gt;

&lt;p&gt;But I mostly glossed over its other technical advantages. First and foremost is the way it is extremely difficult to abuse. Providing access to a resource only through the gateway of a function is practically impossible to get wrong. You can&amp;#8217;t forget to put in the &lt;strong&gt;using&lt;/strong&gt; statement, because you don&amp;#8217;t need one. Nor can you call the &lt;strong&gt;Dispose&lt;/strong&gt; method of nested stack-like resources in the wrong order, because no such method is exposed to you.&lt;/p&gt;

&lt;p&gt;For some kinds of resource, it is not necessary or desirable to force them to exit when an exception occurs. The reason for this is that you would expect an exception to abort the whole operation in which the resource is relevant. An example is the &lt;strong&gt;TraceWriter&lt;/strong&gt; class that I included in the &lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2009/02/displaying-nested-evaluation-tree-from.html"&gt;source code of this post&lt;/a&gt;. It includes this gateway method:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;font color="#0000ff"&gt;void&lt;/font&gt; Indented(Action whileIndented)
{
    WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;{&amp;quot;&lt;/span&gt;);
    _indent++;
    whileIndented();
    _indent--;
    WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;}&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This allows me to write very readable code:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;writer.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;string comparison:&amp;quot;&lt;/span&gt;);
writer.Indented(() =&amp;gt;
    {
        writer.WriteLine(leftValue);
        writer.WriteLine(rightValue);
        writer.WriteLine(&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; &lt;span style="color: #0000ff"&gt;String&lt;/span&gt;(&lt;span style="color: #008000"&gt;' ', index)&lt;/span&gt;
                         + &lt;span style="color: #006080"&gt;&amp;quot;^ difference at index &amp;quot;&lt;/span&gt; + index);
    });&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;It is absolutely impossible for me to forget to un-indent after I&amp;#8217;ve indented, thanks to the use of a gateway function to control the use of the indenting &amp;#8220;resource&amp;#8221;. However, I&amp;#8217;ve made the &lt;strong&gt;Indented&lt;/strong&gt; method completely ignore exceptions, because in this program, if an exception occurs during the logging process, I expect the whole log file to be abandoned anyway. Had this not been the case, I would have use &lt;strong&gt;try&lt;/strong&gt;/&lt;strong&gt;finally&lt;/strong&gt; within &lt;strong&gt;Indented&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Only by writing our own gateway functions can we make the right choice for each case.&lt;/p&gt;

&lt;p&gt;This works for all kinds of resources, of course. It is not only free from the cultural/educational baggage surrounding &lt;strong&gt;IDisposable&lt;/strong&gt;, but it also does a better job technically, giving us control over the handling of exceptions and protecting us from accidental abuses.&lt;/p&gt;

&lt;p&gt;So in summary: where resource-like patterns of state occur in your own programs, I recommend where possible making little gateway functions to provide access to those states, instead encapsulating the resource in an &lt;strong&gt;IDisposable&lt;/strong&gt; class.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-1795195354728745647?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/1795195354728745647/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=1795195354728745647' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/1795195354728745647'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/1795195354728745647'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/02/general-theory-of-resources.html' title='General Theory of Resources'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-3194142449974836406</id><published>2009-02-13T10:25:00.002Z</published><updated>2011-02-04T11:18:49.919Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambdas'/><category scheme='http://www.blogger.com/atom/ns#' term='testing'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='expressions'/><title type='text'>Displaying a nested evaluation tree from Expression&lt;Func&lt;bool&gt;&gt;</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/02/13/displaying-a-nested-evaluation-tree-from-expressionfuncbool/'&lt;/script&gt;

&lt;p&gt;&lt;strong&gt;Updated:&lt;/strong&gt; The downloadable source (see link below) is now tidied up a bit, and also displays any embedded string comparisons in a similar way to NUnit.&lt;/p&gt;  &lt;p&gt;This might be useful as a way to write Assert statements in tests. Instead of requiring many different forms of Assert to capture values and intents, we could just have one Assert that accepts a lambda:&lt;/p&gt;  &lt;div&gt;   &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Assert(Expression&amp;lt;Func&amp;lt;&lt;span style="color: #0000ff"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt; expr)
{
    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (!(&lt;span style="color: #0000ff"&gt;bool&lt;/span&gt;)Trace(expr.Body, 0))
    {
        &lt;span style="color: #008000"&gt;// throw an exception...&lt;/span&gt;
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Now all we need is a &lt;strong&gt;Trace&lt;/strong&gt; function. The challenge is making it include all the relevant information about the test, including the values being used. But this isn't actually that hard, because you just recursively search through the tree of nested expressions, evaluating them all:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;object&lt;/span&gt; Trace(Expression part, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; indent)
{
    &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; indentString = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; String(&lt;span style="color: #006080"&gt;' '&lt;/span&gt;, indent*2);

    Console.Write(indentString);
    Console.Write(GetExpressionText(part));
    Console.Write(&lt;span style="color: #006080"&gt;&amp;quot; == &amp;quot;&lt;/span&gt;);
    LambdaExpression lambda = Expression.Lambda(part);
    Delegate callable = lambda.Compile();
    &lt;span style="color: #0000ff"&gt;object&lt;/span&gt; result = callable.DynamicInvoke(&lt;span style="color: #0000ff"&gt;null&lt;/span&gt;);

    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (result &lt;span style="color: #0000ff"&gt;is&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt;)
        result = &lt;span style="color: #006080"&gt;&amp;quot;\&amp;quot;&amp;quot;&lt;/span&gt; + result + &lt;span style="color: #006080"&gt;&amp;quot;\&amp;quot;&amp;quot;&lt;/span&gt;;

    Console.Write(result);

    &lt;span style="color: #0000ff"&gt;var&lt;/span&gt; nestedExpressions = part
        .GetType()
        .GetProperties()
        .Where(p =&amp;gt; &lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(Expression).IsAssignableFrom(p.PropertyType))
        .Select(p =&amp;gt; (Expression)p.GetValue(part, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;))
        .Where(x =&amp;gt; (x != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;) &amp;amp;&amp;amp; !(x &lt;span style="color: #0000ff"&gt;is&lt;/span&gt; ConstantExpression));

    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (nestedExpressions.Any())
    {
        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot; where&amp;quot;&lt;/span&gt;);
        Console.Write(indentString);
        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;{&amp;quot;&lt;/span&gt;);

        &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (Expression nested &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; nestedExpressions)
            Trace(nested, indent + 1);

        Console.Write(indentString);
        Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;}&amp;quot;&lt;/span&gt;);
    }
    &lt;span style="color: #0000ff"&gt;else&lt;/span&gt;
        Console.WriteLine();

    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; result;
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;I just use reflection and a bit of LINQ to hunt for nested expressions, so I don't need to laboriously handle the various kinds of expression.&lt;/p&gt;

&lt;p&gt;I don't bother presenting the value of constants, because it would just explain to the user that 5 == 5, which isn't very enlightening.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;GetExpressionText&lt;/strong&gt; function is a helper to tidy up the output. Variables captured in the lambda have some nasty looking prefix to identify which compiler-generated class they belong to, but that's unlikely to be useful here, so I strip it out:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; GetExpressionText(Expression expr)
{
    &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; text = expr.ToString();

    &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; prefix = &lt;span style="color: #006080"&gt;&amp;quot;value(&amp;quot;&lt;/span&gt;;
    &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; suffix = &lt;span style="color: #006080"&gt;&amp;quot;).&amp;quot;&lt;/span&gt;;

    StringBuilder builder = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; StringBuilder();

    &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; start = 0;
    &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; pos = text.IndexOf(prefix);
    &lt;span style="color: #0000ff"&gt;while&lt;/span&gt; (pos != -1)
    {
        builder.Append(text.Substring(start, pos - start));
        start = text.IndexOf(suffix, pos) + suffix.Length;
        pos = text.IndexOf(prefix, start);
    }

    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (start &amp;lt; text.Length)
        builder.Append(text.Substring(start, text.Length - start));

    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; builder.ToString();
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;And now for a little demo:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; x = 3;
&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; t = &lt;span style="color: #006080"&gt;&amp;quot;hi&amp;quot;&lt;/span&gt;;
Assert(() =&amp;gt; 5*x + (2 / t.Length) &amp;lt; 99);&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Which produces the remarkably readable output:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;(((5 * x) + (2 / t.Length)) &amp;lt; 99) == True where
{
  ((5 * x) + (2 / t.Length)) == 16 where
  {
    (5 * x) == 15 where
    {
      x == 3
    }
    (2 / t.Length) == 1 where
    {
      t.Length == 2 where
      {
        t == &lt;span style="color: #006080"&gt;&amp;quot;hi&amp;quot;&lt;/span&gt;
      }
    }
  }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Obviously not a hugely strenuous test, but I suspect any other edge cases could easily be dealt with.&lt;/p&gt;

&lt;p&gt;The way I've written &lt;strong&gt;Assert&lt;/strong&gt; is just for demo purposes, because I wanted to see the trace regardless of whether the test passes or fails. In a real framework you'd only print out the trace if the test failed. Apart from making the successful output as short as possible (silence is golden) it would also help your tests run faster.&lt;/p&gt;

&lt;p&gt;Download full source here: &lt;a href="http://www.earwicker.com/blogfiles/ExpressionTracer.zip"&gt;http://www.earwicker.com/blogfiles/ExpressionTracer.zip&lt;/a&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-3194142449974836406?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/3194142449974836406/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=3194142449974836406' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/3194142449974836406'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/3194142449974836406'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/02/displaying-nested-evaluation-tree-from.html' title='Displaying a nested evaluation tree from Expression&amp;lt;Func&amp;lt;bool&amp;gt;&amp;gt;'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-918932669119599154</id><published>2009-02-08T18:51:00.002Z</published><updated>2011-02-04T11:19:12.747Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambdas'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='IDisposable'/><title type='text'>A functional replacement for the using statement</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/02/08/a-functional-replacement-for-the-using-statement/'&lt;/script&gt;

&lt;p&gt;The using-statement is just that: a statement. Why does this bug me?&lt;/p&gt;  &lt;p&gt;The &lt;strong&gt;FileStream&lt;/strong&gt; object has a &lt;strong&gt;Length&lt;/strong&gt; property. Assuming I have a function &lt;strong&gt;Open&lt;/strong&gt; that returns a &lt;strong&gt;FileStream&lt;/strong&gt; ready for us, it is awfully tempting to do this:&lt;/p&gt;  &lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;   &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;     &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;Console.WriteLine(Open().Length);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;But that is wrong, wrong, wrong, because it postpones the closing of the file handle until the finalization thread gets around to it. No good.&lt;/p&gt;

&lt;p&gt;To obtain a value from a disposable object after that object is disposed, you have to store it in a variable declared outside the using-statement, like this:&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;long&lt;/span&gt; length;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (FileStream file = Open())&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    length = file.Length;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;Console.WriteLine(length);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Not very nice. But how about this?&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;Console.WriteLine(Open().Use(file =&amp;gt; file.Length));&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Only a little uglier than the wrong version, but a whole lot righter. The &lt;strong&gt;Use&lt;/strong&gt; extension method executes the function passed to it, and returns whatever that function returns, but also disposes of the object it was called on:&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; DisposableExtensions&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;{&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; TResult Use&amp;lt;TArg, TResult&amp;gt;(&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        &lt;span style="color: #0000ff"&gt;this&lt;/span&gt; TArg arg, Func&amp;lt;TArg, TResult&amp;gt; usage)&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        &lt;span style="color: #0000ff"&gt;where&lt;/span&gt; TArg : IDisposable&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        &lt;span style="color: #0000ff"&gt;try&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;            &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; usage(arg);&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        &lt;span style="color: #0000ff"&gt;finally&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;            arg.Dispose();&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Of course, this technique allows us to do something very similar even when we aren&amp;#8217;t dealing with objects that implement &lt;strong&gt;IDisposable&lt;/strong&gt;. What we are really doing here is putting the system into some temporary state, then computing something, then undoing that temporary state change. That&amp;#8217;s all a&amp;#160; &amp;#8220;resource&amp;#8221; really is: some state the system gets into that you&amp;#8217;ll need to back out of soon. The definition of &amp;#8220;soon&amp;#8221; varies; for memory allocation, we can be pretty lax, because we have enough memory to support a very large number of small allocations simultaneously, but we can only support a single exclusive file handle on a given file, so we have to be extremely careful.&lt;/p&gt;

&lt;p&gt;So a resource is two bits of code: get-into-state and get-out-of-state. Suppose I have a really simple kind of &amp;#8220;lock&amp;#8221;. I actually support any number of simultaneous locks, but I want to know how many are held at any given time. So my &amp;#8220;lock&amp;#8221; is just an integer field in my class. To take out a lock, increment it, and to release the lock, decrement it:&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Lockable&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;{&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; _lockCount;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; OpenLocks&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        get { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; _lockCount; }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Lock()&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        _lockCount++;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Unlock()&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        _lockCount--;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;How can I help users of my class to ensure they don&amp;#8217;t forget to release the lock in a timely fashion?&lt;/p&gt;

&lt;p&gt;If you understood the definition of a &amp;#8220;resource&amp;#8221; I gave above, you&amp;#8217;ll have realised that the resource in this case is not the class itself, but a state in which there has been a call to &lt;strong&gt;Lock&lt;/strong&gt; without a corresponding &lt;strong&gt;Unlock&lt;/strong&gt; call. So if the value of &lt;strong&gt;_lockCount&lt;/strong&gt; happens to be 63, then there are 63 resources alive in our program, and we want them to be cleaned up at some point.&lt;/p&gt;

&lt;p&gt;So the object-oriented (which doesn&amp;#8217;t necessarily mean &amp;#8220;good&amp;#8221;) way to expose this is to &lt;a href="http://en.wikipedia.org/wiki/Reification_(computer_science)"&gt;reify&lt;/a&gt; our resource, by giving it a class of its own:&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Lock : IDisposable&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;{&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;readonly&lt;/span&gt; Lockable _res;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Lock(Lockable res)&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        _res = res;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        _res.Lock();&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Dispose()&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        _res.Unlock();&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Now the users of &lt;strong&gt;MyResource&lt;/strong&gt; can employ the using-statement to call &lt;strong&gt;Dispose&lt;/strong&gt; for them, which takes care of calling &lt;strong&gt;Unlock&lt;/strong&gt;.&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;Lockable mr = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Lockable();&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; locks;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Lock(mr))&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    locks = mr.OpenLocks;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;Console.WriteLine(locks);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Fair enough, but as we saw above, that makes it ugly when we just want to write an expression that computes a value while the lock is held. Yes, we could use my &lt;strong&gt;Use&lt;/strong&gt; extension method:&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;Console.WriteLine(&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Lock(mr).Use(l =&amp;gt; mr.OpenLocks));&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;But why not cut out the middleman altogether?&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Lockable&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;{&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; _lockCount;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; OpenLocks&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        get { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; _lockCount; }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; T WithinLock&amp;lt;T&amp;gt;(Func&amp;lt;T&amp;gt; f)&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        _lockCount++;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        &lt;span style="color: #0000ff"&gt;try&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;            &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; f();&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        &lt;span style="color: #0000ff"&gt;finally&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        {&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;            _lockCount--;&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;        }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;    }&lt;/pre&gt;

    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;We get rid of the public &lt;strong&gt;Lock&lt;/strong&gt;/&lt;strong&gt;Unlock&lt;/strong&gt; so there&amp;#8217;s no way to break the rules, and instead provide a way to conveniently get a parameterless lambda executed inside a lock, guaranteeing that the lock will be released when the computation finishes:&lt;/p&gt;

&lt;div style="border-bottom: gray 1px solid; border-left: gray 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; max-height: 200px; font-size: 8pt; overflow: auto; border-top: gray 1px solid; cursor: text; border-right: gray 1px solid; padding-top: 4px"&gt;
  &lt;div style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;
    &lt;pre style="border-bottom-style: none; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px"&gt;Console.WriteLine(mr.WithinLock(() =&amp;gt; mr.OpenLocks));&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This addresses a very common complaint about &lt;strong&gt;IDisposable&lt;/strong&gt;, which is that the user has to remember to call &lt;strong&gt;Dispose&lt;/strong&gt;, or else they have to remember to use a using-statement, and it is very easy to forget. With the above alternative technique, the user is not given the ability to forget.&lt;/p&gt;

&lt;p&gt;I call such methods &amp;quot;Gateways&amp;quot;, although in Java this is called the &lt;a href="http://stackoverflow.com/questions/341971/what-is-the-execute-around-idiom"&gt;Execute Around&lt;/a&gt; idiom, and it is also exemplified by Common Lisp macros that start with the prefix &lt;strong&gt;with-&lt;/strong&gt;, such as &lt;strong&gt;&lt;a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/mac_with-open-file.html"&gt;with-open-file&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Of course, there is a minor downside. C# has the error: &amp;#8220;Cannot use void as a type argument&amp;#8221;. So you have to write a second version of &lt;strong&gt;WithinLock&lt;/strong&gt; that returns &lt;strong&gt;void&lt;/strong&gt; and accepts an &lt;strong&gt;Action&lt;/strong&gt; as its parameter, of which more in my next post.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-918932669119599154?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/918932669119599154/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=918932669119599154' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/918932669119599154'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/918932669119599154'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/02/functional-replacement-for-using.html' title='A functional replacement for the using statement'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-6934430846297326392</id><published>2009-02-03T15:02:00.002Z</published><updated>2011-02-04T11:19:32.140Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='foreach'/><category scheme='http://www.blogger.com/atom/ns#' term='delegates'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>Further Muddying the ForEach Waters</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/02/03/further-muddying-the-foreach-waters/'&lt;/script&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/kirillosenkov/archive/2009/01/31/foreach.aspx"&gt;ForEach is regularly proposed&lt;/a&gt; as a missing feature in the BCL but has been rejected in the past apparently because it wouldn't be &amp;quot;functional&amp;quot; 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.&lt;/p&gt;  &lt;div&gt;   &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; IEnumerable&amp;lt;Action&amp;gt; ForEach&amp;lt;T&amp;gt;(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; source, 
                                             Action&amp;lt;T&amp;gt; action)
{
    &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (T item &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; source)
    {
        T captured = item;
        yield &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; () =&amp;gt; action(captured);
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;That extension method turns a list of items of any type into a list of actions, by binding a dedicated action to each item. The resulting list can then be operated on further - e.g. interleaved with other lists, reversed, counted, and so on.&lt;/p&gt;

&lt;p&gt;Another useful operation is a specialised form of Aggregate that turns a list of actions into a single action. The CLR already has an efficient representation of this: a multicast delegate, so that's what I prepare and return:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; Action Aggregate(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt; IEnumerable&amp;lt;Action&amp;gt; actions)
{
    Action del = &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;;

    &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (Action action &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; actions)
        del += action;

    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; del;
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;So now I can write things like:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt;[] arr = { 3, 1, 4 };

Action act = arr.ForEach(Console.WriteLine)
            .Concat(arr.ForEach(Console.WriteLine).Reverse())
            .Aggregate();

act();&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;(Oh, how much clearer that would look with &lt;a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=168224"&gt;operator overloading through extension methods&lt;/a&gt;, using + to concatenate the lists, but I digress...)&lt;/p&gt;

&lt;p&gt;Which prints:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;3
1
4
4
1
3&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;So the bound actions generated from the lists can be chained, reversed, rechained, signed in triplicate and finally &lt;a href="http://en.wikipedia.org/wiki/Vogon"&gt;buried for three months and then recycled as firelighters&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;By the way, the feedback from MS on the plain ForEach suggestion is baffling in any case. They don't want to support stateful, imperative programming? Then they need to remove quite a lot of existing features from the language, such as assignment! By all means support functional programming smoothly with C# (a brilliant strategy) but don't get confused into thinking that you're maintaining F#. The whole point of C# is to be the number 1 language for building and using libraries in the CLR, and such libraries are expressed through components that are, for better or worse, brimming with mutable state.&lt;/p&gt;

&lt;p&gt;Meanwhile, you can add features for specifying whether a given data structure is mutable or not, and this will take control of naughty mutation far more effectively than merely failing to add frequently useful features to the BCL.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-6934430846297326392?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/6934430846297326392/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=6934430846297326392' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/6934430846297326392'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/6934430846297326392'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/02/further-muddying-foreach-waters.html' title='Further Muddying the ForEach Waters'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-6056922647035909952</id><published>2009-01-29T13:42:00.002Z</published><updated>2011-02-04T11:20:33.071Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='immutable'/><title type='text'>Using Collection Initializers with Immutable Lists</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/01/29/using-collection-initializers-with-immutable-lists/'&lt;/script&gt;


&lt;p&gt;The &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2009/01/26/benchmarking-made-easy.aspx"&gt;Incomparable Mr Skeet&lt;/a&gt; mentions how irksome it is that collection initializers assume that the collection is mutable.&lt;/p&gt;  &lt;p&gt;Suppose we defined an &amp;quot;immutable-yet-initializable collection&amp;quot; as any type that supports this interface:&lt;/p&gt;  &lt;div&gt;   &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;interface&lt;/span&gt; IImmutableCollection&amp;lt;TCollection, TItem&amp;gt; : IEnumerable&amp;lt;TItem&amp;gt;
       where TCollection : IImmutableCollection&amp;lt;TCollection, TItem&amp;gt;, &lt;span style="color: #0000ff"&gt;new&lt;/span&gt;()
{
    TCollection Add(TItem item);
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;In other words, it can be enumerated, it can be default-constructed (to get an empty list) and it has an Add method that returns a new list with the item added to it.&lt;/p&gt;

&lt;p&gt;And suppose our simple demo implementation of that is as follows:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; SimpleImmutableList&amp;lt;TItem&amp;gt; : 
             IImmutableCollection&amp;lt;SimpleImmutableList&amp;lt;TItem&amp;gt;, TItem&amp;gt;
{
    &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; SimpleImmutableList&amp;lt;TItem&amp;gt; _next;

    &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; TItem _head;

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; SimpleImmutableList&amp;lt;TItem&amp;gt; Add(TItem item)
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; SimpleImmutableList&amp;lt;TItem&amp;gt;
                   {
                       _next = &lt;span style="color: #0000ff"&gt;this&lt;/span&gt;,
                       _head = item
                   };
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; IEnumerator&amp;lt;TItem&amp;gt; GetEnumerator()
    {
        &lt;span style="color: #0000ff"&gt;for&lt;/span&gt; (SimpleImmutableList&amp;lt;TItem&amp;gt; i = &lt;span style="color: #0000ff"&gt;this&lt;/span&gt;; 
             i._next != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;; i = i._next)
            yield &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; i._head;
    }

    System.Collections.IEnumerator 
           System.Collections.IEnumerable.GetEnumerator()
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; GetEnumerator();
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Not very sophisticated, doesn't attempt to solve the well-known &amp;quot;OMG! my list is backward&amp;quot; problem. But anyway. Our problem is that we want this delightful experience:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;List&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt; mutableList = 
        &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; List&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;
                   {
                       &lt;span style="color: #006080"&gt;&amp;quot;First&amp;quot;&lt;/span&gt;,
                       &lt;span style="color: #006080"&gt;&amp;quot;Second&amp;quot;&lt;/span&gt;,
                       &lt;span style="color: #006080"&gt;&amp;quot;Third&amp;quot;&lt;/span&gt;
                   };
Debug.Assert(mutableList.Count() == 3);
Debug.Assert(mutableList.ElementAt(2) == &lt;span style="color: #006080"&gt;&amp;quot;Third&amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Except that we want to make a &lt;strong&gt;SimpleImmutableList&amp;lt;string&amp;gt;&lt;/strong&gt; instead of a &lt;strong&gt;List&amp;lt;string&amp;gt;&lt;/strong&gt;. Well, we can get pretty close:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;SimpleImmutableList&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt; immutableList = 
        &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; &lt;font color="#ff0000"&gt;&lt;strong&gt;Initializer&amp;lt;&lt;/strong&gt;&lt;/font&gt;SimpleImmutableList&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;&lt;font color="#ff0000"&gt;&lt;strong&gt;, string&amp;gt;&lt;/strong&gt;&lt;/font&gt;
                    {
                        &lt;span style="color: #006080"&gt;&amp;quot;First&amp;quot;&lt;/span&gt;,
                        &lt;span style="color: #006080"&gt;&amp;quot;Second&amp;quot;&lt;/span&gt;,
                        &lt;span style="color: #006080"&gt;&amp;quot;Third&amp;quot;&lt;/span&gt;
                    }&lt;font color="#ff0000"&gt;&lt;strong&gt;.Result&lt;/strong&gt;&lt;/font&gt;;
Debug.Assert(immutableList.Count() == 3);
Debug.Assert(immutableList.ElementAt(2) == &lt;span style="color: #006080"&gt;&amp;quot;First&amp;quot;&lt;/span&gt;); // OMG! etc&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;I've picked out in red ink the extra noise we have to add, but it's not that bad. The enabling thing is that &lt;strong&gt;Initializer&lt;/strong&gt; class:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Initializer&amp;lt;TCollection, TItem&amp;gt;  : IEnumerable&amp;lt;TItem&amp;gt;
       where TCollection : IImmutableCollection&amp;lt;TCollection, TItem&amp;gt;, 
                           &lt;span style="color: #0000ff"&gt;new&lt;/span&gt;()
{
    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Initializer()
    {
        Result = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; TCollection();
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Add(TItem item)
    {
        Result = Result.Add(item);
    }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; TCollection Result { get; &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; set; }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; IEnumerator&amp;lt;TItem&amp;gt; GetEnumerator()
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Result.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Result.GetEnumerator();
    }
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;So if anyone tells you that it is impossible to initialize an immutable collection with a collection initializer, tell them about the time you met a crazy old man with some wild ideas about an Initializer class, and see what they say&lt;sup&gt;&lt;font size="2"&gt;1&lt;/font&gt;&lt;/sup&gt;.&lt;/p&gt;

&lt;p&gt;&lt;font size="1"&gt;1. &amp;quot;Get out of my house&amp;quot;.&lt;/font&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-6056922647035909952?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/6056922647035909952/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=6056922647035909952' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/6056922647035909952'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/6056922647035909952'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/01/using-collection-initializers-with.html' title='Using Collection Initializers with Immutable Lists'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-2627219497892724962</id><published>2009-01-26T18:18:00.002Z</published><updated>2011-02-04T17:10:29.249Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambdas'/><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><category scheme='http://www.blogger.com/atom/ns#' term='LINQ'/><title type='text'>Linq to C++0x</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2009/01/26/linq-to-c0x/'&lt;/script&gt;

&lt;p&gt;&lt;em&gt;Updated 2009-01-28 - completely different approach to get a fluent interface.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Updated 2009-05-22 - &lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2009/05/vc16-has-decltype-in-beta-1-so-linq-to.html"&gt;See new post with decltype goodness!&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;C++ has long had some functional-styled things in its standard library, in particular a header file called &amp;lt;functional&amp;gt;. But actually using it in a functional way has been painful, largely due to the lack of lambdas.&lt;/p&gt;  &lt;p&gt;But &lt;a href="http://en.wikipedia.org/wiki/C%2B%2B0x"&gt;C++0x&lt;/a&gt; (very good Wikipedia page, by the way) solves this, amongst many other long-standing problems.&lt;/p&gt;  &lt;p&gt;With lambdas in place, the next thing I naturally wonder is: what about a complete system of lazy-evaluated list processing, which is to say: what about Linq to Objects in C++?&lt;/p&gt;  &lt;p&gt;The C++ equivalent of &lt;strong&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/strong&gt; is a collection of T. Another good thing in C++0x is &lt;a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Concepts"&gt;concepts&lt;/a&gt;, which allows us to state for the first time precisely what we mean by a collection in C++. I don't yet have a compiler that supports concepts, so I'll just say that for the sake of argument, a collection is anything that has a nested type called &lt;strong&gt;const_iterator&lt;/strong&gt; and two const methods called &lt;strong&gt;begin&lt;/strong&gt; and &lt;strong&gt;end&lt;/strong&gt; that return instances of that &lt;strong&gt;const_iterator&lt;/strong&gt; type. (I'm using const iterators because I want to support functional style programming, and support for immutability is one area where C++ still leaves C# in the dust).&lt;/p&gt;  &lt;p&gt;The iterator is the equivalent of &lt;strong&gt;IEnumerator&amp;lt;T&amp;gt;&lt;/strong&gt;, and must have an &lt;strong&gt;*&lt;/strong&gt; operator so we can retrieve the current item, and a &lt;strong&gt;++&lt;/strong&gt; operator so we can navigate to the next item. We discover if we're at the end by comparing the iterator with the instance returned by &lt;strong&gt;end&lt;/strong&gt;, so iterators must also have equality comparison.&lt;/p&gt;  &lt;p&gt;Just as a minimal demonstration, I want to recreate the &lt;strong&gt;Select&lt;/strong&gt; and &lt;strong&gt;Where&lt;/strong&gt; extension methods. They don't actually use any new C++0x features, but as we'll see, they become much more pleasant to use as a result of lambdas.&lt;/p&gt;  &lt;p&gt;In order to share as much code as I can, I'll create a single new container-like class template called &lt;strong&gt;filter&lt;/strong&gt;, which simulates a container by borrowing the contents of another container. It will have built-in features to support skipping over some elements, and to transform elements to new values (not necessarily of the same type).&lt;/p&gt;  &lt;p&gt;Because of this approach, I'll need a way to switch off these features when I don't need them. When deciding whether to skip over an element, we will use a predicate, which is a function that takes some value and returns a &lt;strong&gt;bool&lt;/strong&gt;. To switch off that feature, we'd simply pass a predicate that always returns true:&lt;/p&gt;  &lt;div&gt;   &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; T&amp;gt;
&lt;span style="color: #0000ff"&gt;struct&lt;/span&gt; always_true
{
    &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;() (&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; T &amp;amp;) &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;true&lt;/span&gt;; }
};&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Similarly to switch off element transformation we need a function that just passes through whatever it is given:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; T&amp;gt;
&lt;span style="color: #0000ff"&gt;struct&lt;/span&gt; pass_thru
{
    T &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;() (&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; T &amp;amp;e) &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; e; }
};&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;I could of course re-write these simple functions as lambdas wherever I need them, but as I need them in a couple of places it makes sense to name them in the traditional way.&lt;/p&gt;

&lt;p&gt;And now here's the &lt;strong&gt;filter&lt;/strong&gt; class template.&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TElemFrom, 
          &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TElemTo, 
          &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TIterFrom, 
          &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TSelector,
          &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TPredicate&amp;gt;
&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; filter
{
    TIterFrom from_;
    TIterFrom end_;
    &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TSelector &amp;amp;selector_;
    &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TPredicate &amp;amp;predicate_;

&lt;span style="color: #0000ff"&gt;public&lt;/span&gt;:
    filter(TIterFrom from, TIterFrom end, 
             &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TSelector &amp;amp;selector, 
             &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TPredicate &amp;amp;predicate)
        : from_(from), end_(end), 
          selector_(selector), 
          predicate_(predicate) {}

    &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; const_iterator
    {
        TIterFrom from_;
        TIterFrom end_;
        &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TSelector &amp;amp;selector_;
        &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TPredicate &amp;amp;predicate_;

        &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; locate()
        {
            &lt;span style="color: #0000ff"&gt;while&lt;/span&gt; (!done())
            {
                &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (predicate_(*from_))
                    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt;;

                ++from_;
            }
        }

        &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; done() &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; (from_ == end_); }

    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt;:
        const_iterator(TIterFrom from, TIterFrom end, 
                       &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TSelector &amp;amp;selector,
                       &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TPredicate &amp;amp;predicate)
            : from_(from), end_(end), 
              selector_(selector),
              predicate_(predicate) { locate(); }

        TElemTo &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;*() &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; selector_(*from_); }

        const_iterator &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;++()
        {
            ++from_;
            locate();
            &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; *&lt;span style="color: #0000ff"&gt;this&lt;/span&gt;;
        }

        &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;==(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; const_iterator &amp;amp;other) &lt;span style="color: #0000ff"&gt;const&lt;/span&gt;
            { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; done() &amp;amp;&amp;amp; other.done(); }

        &lt;span style="color: #0000ff"&gt;bool&lt;/span&gt; &lt;span style="color: #0000ff"&gt;operator&lt;/span&gt;!=(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; const_iterator &amp;amp;other) &lt;span style="color: #0000ff"&gt;const&lt;/span&gt;
            { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; !done() || !other.done(); }
    };

    typedef TElemFrom value_type;

    const_iterator begin() &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; 
        { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; const_iterator(from_, end_, selector_, predicate_); }

    const_iterator end() &lt;span style="color: #0000ff"&gt;const&lt;/span&gt; 
        { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; const_iterator(end_, end_, selector_, predicate_); }

    template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TElemTo2, &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TSelector&amp;gt;
    filter&amp;lt;TElemTo, 
             TElemTo2,
             const_iterator, 
             TSelector,
             always_true&amp;lt;TElemTo&amp;gt; &amp;gt;
        select(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TSelector &amp;amp;selector)
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; filter&amp;lt;TElemTo, 
                        TElemTo2, 
                        const_iterator, 
                        TSelector, 
                        always_true&amp;lt;TElemTo&amp;gt; &amp;gt;
                    (begin(), 
                     end(), 
                     selector, 
                     always_true&amp;lt;TElemTo&amp;gt;());
    }

    template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TPredicate&amp;gt;
    filter&amp;lt;TElemTo, 
              TElemTo,
             const_iterator, 
             pass_thru&amp;lt;TElemTo&amp;gt;, 
             TPredicate&amp;gt; 
        where(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TPredicate &amp;amp;predicate)
    {
        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; filter&amp;lt;TElemTo, 
                        TElemTo,
                        const_iterator, 
                        pass_thru&amp;lt;TElemTo&amp;gt;, 
                        TPredicate&amp;gt;
                    (begin(),
                     end(),
                     pass_thru&amp;lt;TElemTo&amp;gt;(), 
                     predicate);
    }
};&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;All the real work is done by the nested &lt;strong&gt;const_iterator&lt;/strong&gt; class, which performs skipping using the predicate in the &lt;strong&gt;++&lt;/strong&gt; operator and performs transformation using the 'selector' in the &lt;strong&gt;*&lt;/strong&gt; operator.&lt;/p&gt;

&lt;p&gt;It's quite an unwieldy class to construct, what with all those type parameters and actual parameters, but we can make it much easier by providing a free function called &lt;strong&gt;from&lt;/strong&gt;:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; TCollFrom&amp;gt;
filter&amp;lt;typename TCollFrom::value_type, 
         typename TCollFrom::value_type,
         typename TCollFrom::const_iterator, 
         pass_thru&amp;lt;typename TCollFrom::value_type&amp;gt;,
         always_true&amp;lt;typename TCollFrom::value_type&amp;gt; &amp;gt;
    from(&lt;span style="color: #0000ff"&gt;const&lt;/span&gt; TCollFrom &amp;amp;from)
{
    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; filter&amp;lt;typename TCollFrom::value_type, 
                    typename TCollFrom::value_type, 
                    typename TCollFrom::const_iterator, 
                    pass_thru&amp;lt;typename TCollFrom::value_type&amp;gt;, 
                    always_true&amp;lt;typename TCollFrom::value_type&amp;gt; &amp;gt;
                (from.begin(), 
                 from.end(), 
                 pass_thru&amp;lt;typename TCollFrom::value_type&amp;gt;(), 
                 always_true&amp;lt;typename TCollFrom::value_type&amp;gt;());
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This does nothing much apart from wrapping a real container inside an instance of &lt;strong&gt;filter&lt;/strong&gt;, and switching off all filtering or transformation, so we can then call the &lt;strong&gt;where&lt;/strong&gt; or &lt;strong&gt;select&lt;/strong&gt; members. As those members also return instances of &lt;strong&gt;filter&lt;/strong&gt;, this gives us a convenient &amp;quot;fluent interface&amp;quot;. Those concerned about performance should be reassured that the compiler ought to be able to inline away all of this syntactical plumbing when it sees the trivial definitions of &lt;strong&gt;pass_thru&lt;/strong&gt; and &lt;strong&gt;always_true&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;For example, filter a list of integers and turn them into quoted strings:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;std::vector&amp;lt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt;&amp;gt; vecInts;
vecInts.push_back(5);
vecInts.push_back(2);
vecInts.push_back(9);

auto filtered = from(vecInts)
    .where([] (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; n) { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; n &amp;gt; 3; })
    .select&amp;lt;std::&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;([] (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; n)
        { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #006080"&gt;&amp;quot;\&amp;quot;&amp;quot;&lt;/span&gt; + 
                 boost::lexical_cast&amp;lt;std::&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;(n) + 
                 &lt;span style="color: #006080"&gt;&amp;quot;\&amp;quot;&amp;quot;&lt;/span&gt;; });

&lt;span style="color: #0000ff"&gt;for&lt;/span&gt; (auto i = filtered.begin(); i != filtered.end(); ++i)
    std::cout &amp;lt;&amp;lt; *i &amp;lt;&amp;lt; std::endl;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;And that prints:&lt;/p&gt;

&lt;p&gt;&amp;quot;5&amp;quot; 
  &lt;br /&gt;&amp;quot;9&amp;quot;&lt;/p&gt;

&lt;p&gt;How is this &lt;strong&gt;select&lt;/strong&gt; function different to &lt;strong&gt;std::transform&lt;/strong&gt;? Because it is evaluated lazily. None of the work is done until we are in the final &lt;strong&gt;for&lt;/strong&gt; loop, and I could break out of that early if I wanted to.&lt;/p&gt;

&lt;p&gt;The one irritation is the fact that I have to tell &lt;strong&gt;select&lt;/strong&gt; what the output value type will be, even though the compiler can lambda deduce it from the lambda in this case. Why can't the compiler join up the dots for us? In fact, in a full implementation of C++0x, it could, but I don't yet have access to such a compiler. Here's how I believe it would work.&lt;/p&gt;

&lt;p&gt;First, we need the &lt;strong&gt;decltype&lt;/strong&gt; keyword, which yields the compile-time type of any expression. Suppose we have something function-like of type &lt;strong&gt;TSelector&lt;/strong&gt;, and we want to know what it would return when called. We also happen to know that it takes one parameter of type &lt;strong&gt;TElemTo&lt;/strong&gt; (because we're taking the output of the previous &lt;strong&gt;filter&lt;/strong&gt;).&lt;/p&gt;

&lt;p&gt;So we need an instance of &lt;strong&gt;TSelector&lt;/strong&gt;:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;TSelector()&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;And then on that, we need to call it, passing it an instance of &lt;strong&gt;TElemTo&lt;/strong&gt;:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;TSelector()(TElemTo())&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;And then we want the type of that expression:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;decltype(TSelector()(TElemTo()))&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Hey presto, we might think: this can replace the &lt;strong&gt;TElemTo2&lt;/strong&gt; type parameter, so callers would no longer need to write &lt;strong&gt;select&amp;lt;std::string&amp;gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;But I suspect this won't work, because it's very likely that &lt;strong&gt;TSelector&lt;/strong&gt; will not be default-constructible (if it is a lambda that captures by reference, for example). The trick in such situations is a &lt;strong&gt;make_ptr&lt;/strong&gt; function:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;template &amp;lt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; T&amp;gt;
T *make_ptr() { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; (T *)0; }&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;It actually returns a NULL pointer of the specified type. We can then define a &lt;strong&gt;make_ref&lt;/strong&gt; that turns that into a reference, and our expression becomes:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;decltype(make_ref&amp;lt;TSelector&amp;gt;()(make_ref&amp;lt;TElemTo&amp;gt;()))&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Of course, if that particular operation was ever executed, it would result in major crash-ola. But it never will be executed; &lt;strong&gt;decltype&lt;/strong&gt; doesn't execute the expression, it just figures out the resulting type.&lt;/p&gt;

&lt;p&gt;Then we can get rid of &lt;strong&gt;TElemTo2&lt;/strong&gt;, and our example call looks like this:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;auto filtered = from(vecInts)
    .where([] (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; n) { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; n &amp;gt; 3; })
    .select([] (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; n) { &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #006080"&gt;&amp;quot;\&amp;quot;&amp;quot;&lt;/span&gt; + 
                         boost::lexical_cast&amp;lt;std::&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;(n) + 
                         &lt;span style="color: #006080"&gt;&amp;quot;\&amp;quot;&amp;quot;&lt;/span&gt;; });&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;I hope &lt;strong&gt;decltype&lt;/strong&gt; makes it into MSVC++ version 16.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-2627219497892724962?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/2627219497892724962/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=2627219497892724962' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/2627219497892724962'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/2627219497892724962'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2009/01/linq-to-c0x.html' title='Linq to C++0x'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-3053284188611221803</id><published>2008-12-16T16:33:00.002Z</published><updated>2011-02-04T17:10:47.483Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='ora'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='regions'/><title type='text'>Ora Stories</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2008/12/16/ora-stories/'&lt;/script&gt;

&lt;p&gt;I've written an &lt;a href="http://www.codeplex.com/ora"&gt;add-in for Visual Studio called Ora&lt;/a&gt;. You can read more about it via that link but here's some background to it.&lt;/p&gt;  &lt;p&gt;It's designed to replace a common use of regions - though I'd call it a common &lt;em&gt;abuse&lt;/em&gt; of regions - so it's called Ora, which means a bunch of things in various languages, but can mean &lt;em&gt;region&lt;/em&gt; in Latin.&lt;/p&gt;  &lt;p&gt;Regions are a feature of C# that generate some controversy, inevitably known as the region wars. Sample posts:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://www.evilrob.org/journal/archives/2006/08/09/c-regions-consi.html"&gt;C# Regions Considered Harmful&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://rkse.blogspot.com/2007/06/c-regions-suck.html"&gt;C# Regions Suck&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://extractmethod.wordpress.com/2008/02/29/just-say-no-to-c-regions/"&gt;Just say No! to C# Regions&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://geekswithblogs.net/PTrippett/archive/2008/08/27/c-regions.-when-to-use-them.aspx"&gt;C# Regions... When to use them?&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I think regions mostly suck, at least in the way they are commonly used. They're a form of comment, so they should come with the same warning as comments:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;strong&gt;Do not redundantly replicate in a comment any information that is clearly stated in the code itself.&lt;/strong&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;With this advice in mind, and applying it consistently to regions as well, it would make little sense to put a region called &lt;font face="Courier New"&gt;Private Static Methods&lt;/font&gt; around all your private static methods - it's already perfectly obvious what they are. It says so completely unambiguously in the code. But of course, one day someone will decide that one of the methods should be public - at which point they either have to remember to physically move the method out of that region, or else the region is no longer correct (which is the ultimate fate of all redundant comments).&lt;/p&gt;  &lt;p&gt;So it's almost distressing to see advice like this being handed out:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://www.csharphelp.com/archives3/archive509.html"&gt;Using Regions to Improve Code Readability&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://trackerrealm.com/blogs/2007/04/make-use-of-regions-when-developing-c.html"&gt;Make Use of #regions When Developing C# .net Code&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I've seen class templates, intended to be used by anyone who is starting a new class, which come ready stocked with over a dozen regions called &lt;font face="Courier New"&gt;Private Fields&lt;/font&gt;, &lt;font face="Courier New"&gt;Static Public Properties&lt;/font&gt;, and so on. Suddenly, instead of writing elegant self-descriptive code, you're filling in a tax form. And when you've captured a simple concept in a class with only a few members, it will contain a dozen empty regions, just in case someone one day wants to put things in it that don't belong in it.&lt;/p&gt;  &lt;p&gt;The only justification I know of for this is that it helps anyone reading the code to navigate it. But as a solution, regions are utterly unworkable, so let's state the actual problem clearly:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;A reader of the code needs to see a simple overview of a class, in which the members have been grouped in various helpful ways, so they can navigate to a member in the source code by clicking on its name in the overview.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So what they need is something that automatically builds such an overview on the fly, directly from the code under the cursor. This is the purpose of &lt;a href="http://www.codeplex.com/ora"&gt;Ora, my add-in for Visual Studio&lt;/a&gt;.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-3053284188611221803?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/3053284188611221803/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=3053284188611221803' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/3053284188611221803'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/3053284188611221803'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2008/12/ora-stories.html' title='Ora Stories'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-2223206448659256045</id><published>2008-12-11T17:40:00.002Z</published><updated>2011-02-04T17:11:05.715Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='monads'/><category scheme='http://www.blogger.com/atom/ns#' term='generics'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>The Maybe Monad in C#</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2008/12/11/the-maybe-monad-in-c/'&lt;/script&gt;

&lt;p&gt;The Maybe Monad is extremely simple. It represents a value that might be there, but might not, and also provides a neat way of working with such values.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.haskell.org/all_about_monads/html/maybemonad.html"&gt;This Haskell-related page&lt;/a&gt; makes it pretty clear:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The Maybe monad embodies the strategy of combining a chain of computations that may each return &lt;code&gt;Nothing&lt;/code&gt; by ending the chain early if any step produces &lt;code&gt;Nothing&lt;/code&gt; as output. It is useful when a computation entails a sequence of steps that depend on one another, and in which some steps may fail to return a value.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Change &lt;font face="Courier New"&gt;Nothing&lt;/font&gt; to &lt;strong&gt;null&lt;/strong&gt; and we're talking in C#. Furthermore, it advises:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;If you ever find yourself writing code like this:&lt;/p&gt;    &lt;pre&gt;case ... of
  Nothing -&amp;gt; Nothing
  Just x  -&amp;gt; case ... of
               Nothing -&amp;gt; Nothing
               Just y  -&amp;gt; ...&lt;/pre&gt;

  &lt;p&gt;you should consider using the monadic properties of &lt;code&gt;Maybe&lt;/code&gt; to improve the code.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Again, translating into C#, we're talking about code like this:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; Role GetRole(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; urlString)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;string&lt;/span&gt;[] url = SplitUrl(urlString);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    RecordCompany company = Music.GetCompany(&lt;span style="color: #006080"&gt;&amp;quot;4ad.com&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (company != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        Band band = company.GetBand(&lt;span style="color: #006080"&gt;&amp;quot;Pixies&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (band != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;            Member member = band.GetMember(&lt;span style="color: #006080"&gt;&amp;quot;David&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (member != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; member.Role;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;As we navigate our way through a graph of objects, we repeatedly have to check whether the road is blocked by a null. When a situation like this occurs inside our nice tidy Linq expression, it makes it look really ugly.&lt;/p&gt;

&lt;p&gt;But how can we improve on this in C#?&lt;/p&gt;

&lt;p&gt;Firstly, we should be clear that a reference variable (such as &lt;strong&gt;company&lt;/strong&gt; in the above code) is ideally suited for representing the Maybe monad. Any class type can be &amp;quot;stored&amp;quot; in a reference, otherwise that reference has the special value &lt;strong&gt;null&lt;/strong&gt;. So don't be misled by &lt;a href="http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx"&gt;the example on this page&lt;/a&gt;; it's correct (it's a great article) but it might make you think that we need to define a special new class to make a monad. In this case, as long as we're referring to class types (rather than unboxed value types), we don't need to.&lt;/p&gt;

&lt;p&gt;What we're observing is that reference types already have one of the operations required by a monad: a &lt;em&gt;Unit&lt;/em&gt; function. By simply assigning a new object to a reference variable, you are storing that object in a location that might have been &lt;strong&gt;null&lt;/strong&gt; before you assigned to it, and may become &lt;strong&gt;null&lt;/strong&gt; again later on. So assignment to the reference variable is the &lt;em&gt;Unit&lt;/em&gt; function for our monad; it's built into the language.&lt;/p&gt;

&lt;p&gt;That's all very well, but what are we actually trying to achieve? Going by the Haskell description, it's as if we'd like to be able to casually write a chunk of code like this:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;RecordCompany company = Music.GetCompany(&lt;span style="color: #006080"&gt;&amp;quot;4ad.com&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;Band band = company.GetBand(&lt;span style="color: #006080"&gt;&amp;quot;Pixies&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;Member member = band.GetMember(&lt;span style="color: #006080"&gt;&amp;quot;David&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; member.Role;&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;If any of those operations returned &lt;strong&gt;null&lt;/strong&gt;, then the return value of the whole thing would be &lt;strong&gt;null&lt;/strong&gt;. But of course we don't always want C# to apply that rule, and how would the compiler figure out when to stop treating a chain of operations in this special way?&lt;/p&gt;

&lt;p&gt;What we're missing from our monad is a &lt;em&gt;Bind&lt;/em&gt; function:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; TOut IfNotNull&amp;lt;TIn, TOut&amp;gt;(&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;this&lt;/span&gt; TIn v, Func&amp;lt;TIn, TOut&amp;gt; f) where TIn : &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                                   where TOut: &lt;span style="color: #0000ff"&gt;class&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (v == &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; f(v);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The type parameters in this generic function constrain us to dealing with class types, so what we have here is an extension method that applies to any reference variable (weird distinction: it makes more sense to think of extension methods applying to the reference variable than to the object stored in the variable, because it's perfectly okay to call an extension method on a &lt;strong&gt;null&lt;/strong&gt; reference variable).&lt;/p&gt;

&lt;p&gt;This extension method takes a function that &amp;quot;transitions&amp;quot; from one object to another. They don't have to be the same type. To see the point of all this, let's see how our ugly code looks if we rewrite it:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Music.GetCompany(&lt;span style="color: #006080"&gt;&amp;quot;4ad.com&amp;quot;&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            .IfNotNull(company =&amp;gt; company.GetBand(&lt;span style="color: #006080"&gt;&amp;quot;Pixies&amp;quot;&lt;/span&gt;))&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;            .IfNotNull(band =&amp;gt; band.GetMember(&lt;span style="color: #006080"&gt;&amp;quot;David&amp;quot;&lt;/span&gt;))&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            .IfNotNull(member =&amp;gt; member.Role);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Now it's all just one expression! Cool!&lt;/p&gt;

&lt;p&gt;(If you're wondering why is this important, there are lots of reasons, but here's one to start you off. The original version of the code was a sequence of statements, so it couldn't be represented by an expression tree, whereas the new version can be.)&lt;/p&gt;

&lt;p&gt;So why is &lt;strong&gt;IfNotNull&lt;/strong&gt; a good &lt;em&gt;Bind&lt;/em&gt; function? It's not immediately obvious that it is, because a Bind function talks to its caller in terms of values wrapped in the monad, but deals in &amp;quot;naked&amp;quot; values with the function passed to it. But &lt;strong&gt;IfNotNull&lt;/strong&gt; uses ordinary reference variables in both situations.&lt;/p&gt;

&lt;p&gt;This is because there is a feature missing from C#. It ought to be possible to somehow tag a reference variable to say that it is definitely not &lt;strong&gt;null&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Response to comment from Marcel:&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The : (colon) operator sounds good, but I'd argue that it's a little inflexible. It's a member access operator, like an alternative to the . (dot) so it works for the example I've given here. But what if the way I'd like to transition to the next object in the chain is by passing the current object as a parameter to some function? For example, look up the next object in a &lt;strong&gt;Dictionary&lt;/strong&gt; with &lt;strong&gt;TryGetValue&lt;/strong&gt;, using the current object as a key. With &lt;strong&gt;IfNotNull&lt;/strong&gt;, the non-null object is given a named reference so I can do whatever I want with it.&lt;/p&gt;

&lt;p&gt;As for verbosity, what I'd really like here is the ability to write what might be called &lt;em&gt;extension operators,&lt;/em&gt; something Microsoft has considered but unfortunately isn't planning to implement anytime soon. These are like a cross between extension methods and operator overloads. &lt;a href="http://stackoverflow.com/questions/172658/operator-overloading-with-c-extension-methods"&gt;This SO question&lt;/a&gt; pretty much covers the idea.&lt;/p&gt;

&lt;p&gt;If that was possible, we could change &lt;strong&gt;IfNotNull&lt;/strong&gt; to a binary operator such as | (pipe), allowing us to pipe values between lambdas like this:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Music.GetCompany(&lt;span style="color: #006080"&gt;&amp;quot;4ad.com&amp;quot;&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        | company =&amp;gt; company.GetBand(&lt;span style="color: #006080"&gt;&amp;quot;Pixies&amp;quot;&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        | band =&amp;gt; band.GetMember(&lt;span style="color: #006080"&gt;&amp;quot;David&amp;quot;&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        | member =&amp;gt; member.Role;&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;I think that would be just about perfect.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-2223206448659256045?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/2223206448659256045/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=2223206448659256045' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/2223206448659256045'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/2223206448659256045'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2008/12/maybe-monad-in-c.html' title='The Maybe Monad in C#'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-7924857041620641961</id><published>2008-12-10T11:01:00.002Z</published><updated>2011-02-04T17:11:28.775Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambdas'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='LINQ'/><category scheme='http://www.blogger.com/atom/ns#' term='expressions'/><title type='text'>Optimizing Aggregate for String Concatenation</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2008/12/10/optimizing-aggregate-for-string-concatenation/'&lt;/script&gt;

&lt;p&gt;Linq lets you think in a very generally applicable way and solve a very wide variety of problems with a few key concepts. That’s a great thing. But it’s irritating when the elegant solution doesn’t perform as well as an ugly special case.&lt;/p&gt;  &lt;p&gt;Using a combination of well-known Linq features I’m going to demonstrate that we already have the power to get the best of both worlds: speed and elegance.&lt;/p&gt;  &lt;p&gt;One example that has always irked me (and which is simple enough to demonstrate the idea with) is this:&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;   &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;     &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;Enumerable.Range(0, size) &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;          .Select(n =&amp;gt; n.ToString())&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;          .Aggregate((a, b) =&amp;gt; a + &lt;span style="color: #006080"&gt;&amp;quot;, &amp;quot;&lt;/span&gt; + b);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;It’s got all the attributes of a beautiful Linq-style solution – a single expression that produces the thing we want, using very general operations that are parameterized by self-contained functions.&lt;/p&gt;

&lt;p&gt;But if &lt;strong&gt;size&lt;/strong&gt; gets large, it’s dreadfully slow. The reason is that &lt;strong&gt;Aggregate&lt;/strong&gt; takes the first two items, uses the function to combine them, then you can kind of imagine it putting the result back on the start of the list to replace the original two items. So each time it does that, the list shrinks, until eventually there’s only one item left, which it returns. All very logical and beautiful – the items on the list are from a set and we have defined a closed binary operation on them, so I guess it’s a &lt;a href="http://en.wikipedia.org/wiki/Magma_(algebra)"&gt;magma&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;But that first item is an ever-growing string, and each time around it has to be copied into a new string. This is a recipe for disastrous performance. To get faster performance, we need to use a different function, which I’ll call &lt;strong&gt;Oggregate&lt;/strong&gt;:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Oggregate(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt; IEnumerable&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt; source, &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; delimiter)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    StringBuilder builder = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; StringBuilder();&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    builder.Append(source.First());&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; s &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; source.Skip(1))&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        builder.Append(delimiter);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        builder.Append(s);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; builder.ToString();&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;But this is irksome, because you have to know when to use this optimized version, and then you have to know how to modify your original code. You can’t just flick the “go faster” switch.&lt;/p&gt;

&lt;p&gt;A good programming language defines general concepts that compose (go together) well. A good compiler then takes programs written in that language and does terrifying things to them, without telling you, so that they still do what you asked, but they do it fast. The compiler does this by spotting patterns and saying “Ah, I see what you’re trying to do. I know a faster way to do that.” You don’t have to explicitly tell it to do it the fast way. It just notices the pattern and makes the smart decision. Such capabilities are called compiler optimizations. They’re “turnkey” solutions, in the sense that all you have to do is turn the key and they start up. You don’t typically have to think too hard about it. Somebody already did that for you.&lt;/p&gt;

&lt;p&gt;So my ideal solution for the above problem would be for the compiler (or a library) to notice the pattern I’m using and use the &lt;strong&gt;StringBuilder&lt;/strong&gt; approach instead. If I’m not using that pattern, it should fall back to doing what it usually does.&lt;/p&gt;

&lt;p&gt;I can’t change the compiler, so can I write a library? The problems facing us are three fold:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;We want to replace the standard library’s version of an algorithm that can operate on any sequence.&lt;/li&gt;

  &lt;li&gt;We only want to do that for sequences of strings.&lt;/li&gt;

  &lt;li&gt;We only want to do it if the function parameter has a very narrowly-defined shape.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Skipping the first one for now, the solution to the second problem is to write a version of &lt;strong&gt;Aggregate&lt;/strong&gt; for the special case of string sequences. The solution to the third is clearly going to involve Linq expressions, as they give us a way to examine the structure of simple expression-like functions, and also to apply such a function to some parameters if necessary:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Aggregate(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt; IEnumerable&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt; source, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                 Expression&amp;lt;Func&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;, &lt;span style="color: #0000ff"&gt;string&lt;/span&gt;, &lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; func)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    ... look at the func to decide what to do&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Having defined such a function in some namespace, what happens if we add a &lt;strong&gt;using&lt;/strong&gt; directive at the top of the source file where we want to use it? That’s no good, because the compiler has two choices for which function to use. In C++, the thing we’ve written is a kind of “template specialization”, and the rules for template resolution in C++ usually mean that the most specialized choice is the one that the compiler picks. But this isn’t the case in C#. The compiler just gives up and says that we’re being ambiguous.&lt;/p&gt;

&lt;p&gt;But if we put our &lt;strong&gt;using&lt;/strong&gt; directive inside a &lt;strong&gt;namespace&lt;/strong&gt; block, then the C# compiler is happy to assume that it should select our version of &lt;strong&gt;Aggregate&lt;/strong&gt;:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Linq;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Diagnostics;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;namespace&lt;/span&gt; ConsoleApplication5&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;using&lt;/span&gt; Optimizations.AggregateStringBuilder;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Program&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Main(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;[] args)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        {&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The location of the &lt;strong&gt;using&lt;/strong&gt; directive affects the overload resolution priority assigned to the functions in that namespace. So we can switch on our optimisation at the level of a &lt;strong&gt;namespace&lt;/strong&gt; block. I’m satisfied with that – it constitutes an on/off switch, for my purposes.&lt;/p&gt;

&lt;p&gt;Here’s what the &lt;strong&gt;Aggregate&lt;/strong&gt; function looks like:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Aggregate(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt; IEnumerable&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt; source, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                        Expression&amp;lt;Func&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;, &lt;span style="color: #0000ff"&gt;string&lt;/span&gt;, &lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; func)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    BinaryExpression root = func.Body &lt;span style="color: #0000ff"&gt;as&lt;/span&gt; BinaryExpression;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (root != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (root.NodeType == ExpressionType.Add)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;            BinaryExpression left = root.Left &lt;span style="color: #0000ff"&gt;as&lt;/span&gt; BinaryExpression;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (left != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;            {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (left.NodeType == ExpressionType.Add)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                    ParameterExpression leftLeft = &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                        left.Left &lt;span style="color: #0000ff"&gt;as&lt;/span&gt; ParameterExpression;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (leftLeft != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                        ConstantExpression leftRight = &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                            left.Right &lt;span style="color: #0000ff"&gt;as&lt;/span&gt; ConstantExpression;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                        &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (leftRight != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                        {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                            ParameterExpression right = &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                                root.Right &lt;span style="color: #0000ff"&gt;as&lt;/span&gt; ParameterExpression;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                            &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (right != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                            {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                                &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; ((leftLeft.Name == func.Parameters[0].Name) &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                                  &amp;amp;&amp;amp; (right.Name == func.Parameters[1].Name))&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                                    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; source.Oggregate(&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                                        (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;)leftRight.Value);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                            }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                        }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                    }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;            }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; source.Aggregate(func.Compile());&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;In other words, it looks pretty ugly. But that’s optimizations for you. It really just looks at the lambda to see if it fits a very rigid pattern: (a + c) + b, where a and b are the parameters to the lambda and c is a constant. If so, it calls &lt;strong&gt;Oggregate&lt;/strong&gt;. Otherwise, it falls back to letting the compiler run the lambda as it usually would. A compiled delegate doesn’t match our &lt;strong&gt;Expression&amp;lt;T&amp;gt;&lt;/strong&gt; argument, so the normal version of &lt;strong&gt;Aggregate&lt;/strong&gt; is called.&lt;/p&gt;

&lt;p&gt;This means that, where it’s an appropriate optimization, all it does is examine a few &lt;strong&gt;enum&lt;/strong&gt; properties, perform a few casts, compare a couple of strings and then call &lt;strong&gt;Oggregate&lt;/strong&gt;. So all the extra work (which is very minor) happens outside the loop.&lt;/p&gt;

&lt;p&gt;The remaining question is, how badly does it &lt;em&gt;hurt &lt;/em&gt;performance when it isn’t an appropriate optimization? As usual, it depends greatly on how you use it. If you’re using Aggregate to concatenate a small number of strings, the compilation step is wasteful to be sure. But again, it happens outside the loop. And in any case, if you find that your program runs slower, it’s just as easy to switch off the optimization as it is to switch it on.&lt;/p&gt;

&lt;p&gt;So in conclusion, although this example is pretty simple and so not exactly earth-shattering in itself, it serves to demonstrate how C# gives us the tools to introduce our own turnkey optimizations for special cases of the very general algorithms available in Linq, which was a pleasant surprise for me.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I posted this as a &lt;/em&gt;&lt;a href="http://stackoverflow.com/questions/354587/optimizing-aggregate-for-string-concatenation"&gt;&lt;em&gt;quiz question on Stack Overflow&lt;/em&gt;&lt;/a&gt;&lt;em&gt;. The reaction to the idea of someone posting a question as a quiz was quite mixed – the votes for the question went negative a few times before averaging out at zero. I think this is a good use of the site, because the end result is a question with an answer and some associated discussion to give more detailed background, alternative approaches, etc. I think it annoyed people who didn’t know the answer, because (as I would freely admit) part of the reward of using Stack Overflow is the ego-boost of handing out knowledge to those in need. If you meet someone who already knows the answer to their question, and then – even worse – you don’t know the answer, then it kind of spoils the fun for you (one guy in particular seemed quite upset). But the fact remains that such an exercise produces the same kind of valuable addition to the site.&lt;/em&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-7924857041620641961?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/7924857041620641961/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=7924857041620641961' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/7924857041620641961'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/7924857041620641961'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2008/12/optimizing-aggregate-for-string.html' title='Optimizing Aggregate for String Concatenation'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-6212275531910015173</id><published>2008-12-09T13:44:00.002Z</published><updated>2011-02-04T17:11:48.334Z</updated><title type='text'>Other Examples of Iterators and Async IO</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2008/12/09/other-examples-of-iterators-and-async-io/'&lt;/script&gt;

&lt;p&gt;The idea of &lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2008/12/more-on-jeffrey-richters.html"&gt;returning functions via yield return&lt;/a&gt; to simply asynchronous IO programming has a precedent in Microsoft's Concurrency and Coordination Runtime:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/bb648753.aspx"&gt;http://msdn.microsoft.com/en-us/library/bb648753.aspx&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Although they are yielding interfaces, really they are yielding functions:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/microsoft.ccr.core.itask_members.aspx"&gt;http://msdn.microsoft.com/en-us/library/microsoft.ccr.core.itask_members.aspx&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The &lt;strong&gt;ITask&lt;/strong&gt; interface has only one really important method: &lt;strong&gt;Execute&lt;/strong&gt;, which means that really it's a function (a delegate in C# terms). I think the functional style makes the whole thing cleaner, but the point is that the idea was already in use in the Microsoft's CCR, perhaps as long ago as 2005 (although that's difficult to verify).&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-6212275531910015173?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/6212275531910015173/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=6212275531910015173' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/6212275531910015173'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/6212275531910015173'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2008/12/other-examples-of-iterators-and-async.html' title='Other Examples of Iterators and Async IO'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-4970907164211815174</id><published>2008-12-06T23:34:00.002Z</published><updated>2011-02-04T17:12:13.075Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambdas'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='yield return'/><title type='text'>More on Jeffrey Richter’s AsyncEnumerator and Functional Programming</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2008/12/06/more-on-jeffrey-richter%E2%80%99s-asyncenumerator-and-functional-programming/'&lt;/script&gt;

&lt;p&gt;If you do asynchronous programming (or have been put off it in the past by the complexity) and you haven’t already looked at this, then you really should:&lt;/p&gt;  &lt;p&gt;&lt;a title="http://msdn.microsoft.com/en-us/magazine/cc546608.aspx" href="http://msdn.microsoft.com/en-us/magazine/cc546608.aspx"&gt;http://msdn.microsoft.com/en-us/magazine/cc546608.aspx&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;I blogged yesterday about an idea for doing the same kind of thing but using lambdas to encapsulate the last remaining bit of complexity. Today I’ve applied the same idea, but with the goal of providing a thin layer that works along with Jeffrey Richter’s &lt;strong&gt;AsyncEnumerator&lt;/strong&gt; class, essentially providing an optional new way of working with it. As I am not especially familiar with the asynchronous APIs, it would be especially stupid for me to try and reinvent the wheel instead of building on the work Jeffrey has already done.&lt;/p&gt;  &lt;p&gt;I should point out that everything in this article is provided “as is”, but even more so than people usually mean by that phrase, because &lt;em&gt;I haven’t even tried running any of this code&lt;/em&gt; (although it does compile, at least). I’ve merely attempted to analytically prove (by substitution and expansion) that it produces the equivalent of something that works.&lt;/p&gt;  &lt;p&gt;These are just ideas. I don’t currently have a need for this facility in my own work, so I can’t afford to invest in testing it. I just got carried away with the implications of an idea today, and here are the results of that.&lt;/p&gt;  &lt;p&gt;I’ll start by explaining the nuts and bolts. Using pure functional programming techniques, I’ve defined a handful of static functions, mostly extension methods on pre-existing types, making them very easy to discover and use. To begin with, I’ll leave out a detail to do with exception handling, and then add it in as an afterthought, as it makes things a little messier.&lt;/p&gt;  &lt;p&gt;Jeffrey’s&lt;strong&gt; AsyncEnumerator&lt;/strong&gt; class is effectively a consumer of a sequence of integers. The sequence is generated by a function that the user writes, taking advantage of the &lt;strong&gt;yield return&lt;/strong&gt; keyword. They yield a count of 1 for each asynchronous operation that they start:&lt;/p&gt;  &lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;   &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;     &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;stream.BeginWrite(outputData, 0, outputData.Length, ae.End(), &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 1;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;stream.EndWrite(ae.DequeueAsyncResult());&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;In the above snippet (taken from Jeffrey’s TcpClient example), a single write is made. Characteristically, there are three steps:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Call a BeginXXX API to launch the asynchronous operation. Such operations always require a callback function, which is provided by calling &lt;strong&gt;AsyncEnumerator.End&lt;/strong&gt;. &lt;/li&gt;

  &lt;li&gt;Yield the value 1 (because only one operation has been launched in this case). &lt;/li&gt;

  &lt;li&gt;Call an EndXXX API to finish the operation. The &lt;strong&gt;AsyncEnumerator.DequeueAsyncResult&lt;/strong&gt; is used to obtain some data associated with results of the operation. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The integers so yielded are interpreted as requests to wait for that number of asynchronous operations to complete. So to do three operations in parallel, you would begin three asynchronous calls, and then &lt;strong&gt;yield return 3&lt;/strong&gt;. When your function got back control, the three calls would all have completed. However, they may of course complete in any order, so when the results are dequeued some care may need to be taken in matching the results up with their corresponding EndXXX functions, because they may be of different types (e.g. a stream operation and a WebRequest).&lt;/p&gt;

&lt;p&gt;Using Linq’s &lt;strong&gt;Select&lt;/strong&gt; function, we can easily convert between sequence types. This means that we can provide a way for the user to write a function that yields a sequence of some other kind, such that it can still be plugged into &lt;strong&gt;AsyncEnumerator&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The elements of the new kind of sequence are called activities. Although most user need not be aware of this, they are in fact functions, defined by this delegate:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;delegate&lt;/span&gt; &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; Activity(AsyncEnumerator asyncEnum);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;An activity launches one or more asynchronous operations, and returns how many it has launched, making it perfect to fit &lt;strong&gt;AsyncEnumerator&lt;/strong&gt;’s requirements. So we can easily convert a sequence of these activities into the kind of sequence that &lt;strong&gt;AsyncEnumerator&lt;/strong&gt; likes to get:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Execute(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt; AsyncEnumerator asyncEnum, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                                   IEnumerable&amp;lt;Activity&amp;gt; activities)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    asyncEnum.Execute(activities.Select(activity =&amp;gt; activity(asyncEnum))&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                                .GetEnumerator());&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;In other words, we simply produce a sequence of integers by calling each activity in the input sequence. Then as a final step, get the &lt;strong&gt;IEnumerator&amp;lt;int&amp;gt;&lt;/strong&gt; of the sequence and pass it to the intrinsic &lt;strong&gt;AsyncEnumerator.Execute&lt;/strong&gt; function. By providing this as an extension method, it’s as convenient to use as its intrinsic cousin.&lt;/p&gt;

&lt;p&gt;How can we compose a set of activities to make a single activity that causes all the activities in the set to execute in parallel? By defining a higher-order function that does it for us:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; Activity Parallel(&lt;span style="color: #0000ff"&gt;params&lt;/span&gt; Activity[] list)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; asyncEnum =&amp;gt; list.Sum(activity =&amp;gt; activity(asyncEnum));&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Again, the implementation is trivial thanks to Linq. Our composite activity has to return the sum of the return values of the activities on the input list, so it’s the perfect fit for the &lt;strong&gt;Sum&lt;/strong&gt; function, which adds together the values produced by a function executed for each item in a sequence.&lt;/p&gt;

&lt;p&gt;Finally, we need a higher-order function to allow us to easily define an activity. This one’s a little more mind-bending, but still pretty short. Crucially, it is much easier to use than it is to fully understand, and even then most users do not need to use it directly.&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; Activity Pair(Action&amp;lt;AsyncCallback&amp;gt; begin, AsyncCallback end)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; asyncEnum =&amp;gt; &lt;span style="color: #008000"&gt;// action accepts an AsyncEnumerator &lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        begin(result =&amp;gt; &lt;span style="color: #008000"&gt;// callback accepts a result&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;           {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;               end(result); &lt;span style="color: #008000"&gt;// pass on to the user's handler&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;               asyncEnum.End()(result); &lt;span style="color: #008000"&gt;// and to AsyncEnumerator&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;               asyncEnum.DequeueAsyncResult(); &lt;span style="color: #008000"&gt;// we don't need this&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;           });&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 1;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    };&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;It pairs together two functions. The first one, &lt;strong&gt;begin&lt;/strong&gt;, is responsible for launching the asynchronous call. To do this, it needs a callback function that it can pass to whatever asynchronous API it calls. The second one, &lt;strong&gt;end&lt;/strong&gt;, will run when the call completes, and (as you will see if you look up the definition of the standard &lt;strong&gt;AsyncCallback&lt;/strong&gt; delegate) accepts an &lt;strong&gt;IAsyncResult&lt;/strong&gt; object.&lt;/p&gt;

&lt;p&gt;So the &lt;strong&gt;Activity&lt;/strong&gt; function returned by &lt;strong&gt;Pair&lt;/strong&gt; will call the &lt;strong&gt;begin&lt;/strong&gt; function, and pass it a function to serve as the callback for the asynchronous API. That function is defined by the inner lambda. It calls onto three things:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Firstly, the &lt;strong&gt;end&lt;/strong&gt; function (whatever that may be) so that the result of the call can be interpreted. &lt;/li&gt;

  &lt;li&gt;Secondly, the callback supplied by &lt;strong&gt;AsyncEnumerator&lt;/strong&gt;. This is crucial, as it ensures that the thread pool is asked to execute another step through of the sequence of integers. &lt;/li&gt;

  &lt;li&gt;Finally, the &lt;strong&gt;AsyncEnumerator.DequeAsyncResult&lt;/strong&gt; function, although the result is discarded. This is because we have already passed the result to the end function. But we should still call this function once for each call that is made, so that the queue doesn’t needlessly grow in length. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s all we need as a basis. But for maximum convenience for most users, we can add extension methods for the most commonly used asynchronous call types. For example, writing to a stream:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; Activity RequestWrite(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt; Stream stream, &lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[] buffer, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                                    &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; offset, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; size)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Pair(&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        callback =&amp;gt; stream.BeginWrite(buffer, offset, size, callback, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;),&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        result =&amp;gt; stream.EndWrite(result));&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;This is a higher order function – it makes an Activity function, using the handy Pair function to tie together the two halves of the operation. But it can be called directly on a Stream object. If so called, it does not actually do anything; the return value must be passed on via &lt;strong&gt;yield return&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;So how does code look using this whole technique? Let’s look back at that real example again. The function starts with this signature:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; IEnumerator&amp;lt;Int32&amp;gt; Process(AsyncEnumerator ae, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                                          String server, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                                          String message) &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Then in the body of the function there are triplets of lines like this:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;stream.BeginWrite(outputData, 0, outputData.Length, ae.End(), &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 1;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;stream.EndWrite(ae.DequeueAsyncResult());&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;By contrast, the alternative way of working enabled by these new functions begins by declaring the function like so:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; IEnumerable&amp;lt;Activity&amp;gt; Process(String server, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                                             String message)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;{&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The first thing to note (aside from the obvious change to the return type) is that there is no need to pass in an &lt;strong&gt;AsyncEnumerator&lt;/strong&gt; object, even though it interoperates with one automatically. The code to write to the stream looks like this:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; stream.RequestWrite(outputData, 0, outputData.Length);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The triplet of lines has been boiled down to a single line, which appears just like a non-asynchronous call but with &lt;strong&gt;yield return&lt;/strong&gt; in front of it.&lt;/p&gt;

&lt;p&gt;Because the helper extensions are higher order functions, the user doesn’t need to even be aware that they’re using functional programming, or that an &lt;strong&gt;Activity&lt;/strong&gt; is a function. They just make a method call that appears to do what they want, although they prefix it with &lt;strong&gt;yield return&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;What about parallel activities running at the same time? Loosely inspired by another of Jeffrey’s examples, this function obtains results from two website simultaneously:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; IEnumerable&amp;lt;Activity&amp;gt; ProcessAllAndEachOps()&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;   &lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Async.Parallel(&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;            WebRequest.Create(&lt;span style="color: #006080"&gt;&amp;quot;http://www.google.com&amp;quot;&lt;/span&gt;).RequestResponse(&lt;span style="color: #0000ff"&gt;true&lt;/span&gt;, response =&amp;gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Bytes from Google: &amp;quot;&lt;/span&gt; + response.ContentLength)),&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            WebRequest.Create(&lt;span style="color: #006080"&gt;&amp;quot;http://www.microsoft.com&amp;quot;&lt;/span&gt;).RequestResponse(&lt;span style="color: #0000ff"&gt;true&lt;/span&gt;, response =&amp;gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;Bytes from Microsoft&amp;quot;&lt;/span&gt; + response.ContentLength))&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;       );&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;   Console.WriteLine(&lt;span style="color: #006080"&gt;&amp;quot;All the operations completed.&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Parallel&lt;/strong&gt; function we saw defined above takes care of composing a set of activities into a new activity that will launch all of them to run in parallel.&lt;/p&gt;

&lt;p&gt;The end result appears so simple that it is worth going through an exercise of “expansion” to see how this alternative way of working must produce the same results as the original way. Hold onto your hats…&lt;/p&gt;

&lt;p&gt;Here’s the nice and easy way it looks to the typical user:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; stream.RequestWrite(outputData, 0, outputData.Length);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Let’s substitute in the definition of &lt;strong&gt;RequestWrite&lt;/strong&gt;:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; Async.Pair(&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    callback =&amp;gt; stream.BeginWrite(outputData, 0, outputData.Length, callback, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;),&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    result =&amp;gt; stream.EndWrite(result));&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Then the definition of &lt;strong&gt;Pair&lt;/strong&gt;, in two stages to make it easy to follow. Firstly, keeping the definitions of &lt;strong&gt;begin&lt;/strong&gt; and &lt;strong&gt;end&lt;/strong&gt; separated out:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; asyncEnum =&amp;gt; &lt;span style="color: #008000"&gt;// action accepts an AsyncEnumerator &lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    Action&amp;lt;AsyncCallback&amp;gt; begin =&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;              callback =&amp;gt; stream.BeginWrite(outputData, 0, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                            outputData.Length, callback, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    AsyncCallback end = result =&amp;gt; stream.EndWrite(result);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    begin(result =&amp;gt; &lt;span style="color: #008000"&gt;// callback accepts a result&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        end(result); &lt;span style="color: #008000"&gt;// pass on to the user's handler&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        asyncEnum.End()(result); &lt;span style="color: #008000"&gt;// and to AsyncEnumerator&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        asyncEnum.DequeueAsyncResult(); &lt;span style="color: #008000"&gt;// we don't need this&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    });&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 1;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;};&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Then finally substituting those definitions into their places:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; asyncEnum =&amp;gt; &lt;span style="color: #008000"&gt;// action accepts an AsyncEnumerator &lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    stream.BeginWrite(outputData, 0, outputData.Length, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        result =&amp;gt; &lt;span style="color: #008000"&gt;// callback accepts a result&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;          stream.EndWrite(result); &lt;span style="color: #008000"&gt;// pass on to the user's handler&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;          asyncEnum.End()(result); &lt;span style="color: #008000"&gt;// and to AsyncEnumerator&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;          asyncEnum.DequeueAsyncResult(); &lt;span style="color: #008000"&gt;// we don't need this&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        }, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 1;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;};&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Now we can see what’s really happening. The statement yields a function that calls &lt;strong&gt;BeginWrite&lt;/strong&gt; on the stream and then returns 1. &lt;strong&gt;BeginWrite&lt;/strong&gt; requires a callback, and we build one for it. In the normal way of using &lt;strong&gt;AsyncEnumerator &lt;/strong&gt;as seen in Jeffrey’s example, the callback is provided by calling &lt;strong&gt;AsyncEnumerator.End&lt;/strong&gt;, but here we effectively wrap that in a lambda so we can do other things as well. First we call &lt;strong&gt;EndWrite&lt;/strong&gt; on the stream (which may throw an exception, but I’ll deal with that in a moment), then we call on to the callback returned by &lt;strong&gt;AsyncEnumerator.End&lt;/strong&gt;, and finally we do the housekeeping of discarding one &lt;strong&gt;IAsyncResult&lt;/strong&gt; instance from &lt;strong&gt;AsyncEnumerator&lt;/strong&gt;’s internal inbox.&lt;/p&gt;

&lt;p&gt;Then this whole function will be executed by the &lt;strong&gt;Execute&lt;/strong&gt; extension method. Some more substitution will make this clearer. Here’s the expression we use to generate the kind of &lt;strong&gt;IEnumerable&amp;lt;int&amp;gt;&lt;/strong&gt; that the intrinsic &lt;strong&gt;Execute&lt;/strong&gt; method requires:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;activities.Select(activity =&amp;gt; activity(asyncEnum))&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;So each activity is called in turn to produce integers, and the result is the same as if the return value of the activity was being yielded directly. In other words, continuing our expansion (now supposing we are in a function that is yielding integers having been passed the parameter &lt;strong&gt;asyncEnum&lt;/strong&gt;):&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;stream.BeginWrite(outputData, 0, outputData.Length,&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    result =&amp;gt; &lt;span style="color: #008000"&gt;// callback accepts a result&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        stream.EndWrite(result); &lt;span style="color: #008000"&gt;// pass on to the user's handler&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        asyncEnum.End()(result); &lt;span style="color: #008000"&gt;// and to AsyncEnumerator&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        asyncEnum.DequeueAsyncResult(); &lt;span style="color: #008000"&gt;// we don't need this&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    }, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 1;&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;It is now clear what the only actual differences are. Compare with Jeffrey’s original code (I’ll repeat it here one more time to save you scrolling up and down the page).&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;stream.BeginWrite(outputData, 0, outputData.Length, ae.End(), &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 1;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;stream.EndWrite(ae.DequeueAsyncResult());&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;There, the &lt;strong&gt;End()&lt;/strong&gt; callback causes the function to resume executing after the operation finishes, and the next line of code is the call to &lt;strong&gt;stream.EndWrite&lt;/strong&gt;. Working the new way, &lt;strong&gt;stream.EndWrite&lt;/strong&gt; is called from within the callback itself. It also has the correct &lt;strong&gt;IAsyncResult&lt;/strong&gt; ready to use.&lt;/p&gt;

&lt;p&gt;Also, immediately after calling the function returned by &lt;strong&gt;End()&lt;/strong&gt;, the result is removed from the inbox by calling &lt;strong&gt;DequeAsyncResult&lt;/strong&gt;. This places an additional thread-safety constraint on &lt;strong&gt;AsyncEnumerator&lt;/strong&gt;, because previously it looks like the inbox is only accessed by one thread at a time. But by looking at the code of &lt;strong&gt;AsyncEnumerator&lt;/strong&gt; in Reflector, I can see that it takes out a lock before accessing the queue, so this should be fine.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;So what are the limitations of this new approach? The main one is the lack of flexibility in exception handling. With the original raw approach, you are free to place a try/catch around either the BeginXXX or EndXXX calls (although you can’t place one such handler around both calls, due to a &lt;a href="http://stackoverflow.com/questions/346365/why-cant-yield-return-appear-inside-a-try-block-with-a-catch"&gt;limitation of the yield return implementation&lt;/a&gt;.)&lt;/p&gt;

&lt;p&gt;In the new approach, the best we can do is to allow any exceptions to propagate out of the &lt;strong&gt;IEnumerator&amp;lt;int&amp;gt;&lt;/strong&gt; sequence generator. In other words, if the BeginXXX or EndXXX calls throw an exception, then it is just as if they were to throw uncaught exceptions in the original approach.&lt;/p&gt;

&lt;p&gt;To achieve this, we need to make a further change. The reason is that the EndXXX call is made in the context of a thread that is running due to the fact that an asynchronous call has completed. We do not control that thread. Rather than bothering it with an exception, we need to transfer the exception into the context of whichever thread is executing our function.&lt;/p&gt;

&lt;p&gt;To achieve this, first we have to catch the exception. The user’s callback is executed in the inner lambda in &lt;strong&gt;Pair&lt;/strong&gt;, so that’s where we need a try/catch block:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; Activity Pair(Action&amp;lt;AsyncCallback&amp;gt; begin, AsyncCallback end)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; asyncEnum =&amp;gt; &lt;span style="color: #008000"&gt;// action accepts an AsyncEnumerator &lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        begin(result =&amp;gt; &lt;span style="color: #008000"&gt;// callback accepts a result&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;            &lt;span style="color: #0000ff"&gt;try&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                end(result); &lt;span style="color: #008000"&gt;// pass on to the user's handler&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;            &lt;span style="color: #0000ff"&gt;catch&lt;/span&gt; (Exception e)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                asyncEnum.Cancel(e);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;            asyncEnum.End()(result); &lt;span style="color: #008000"&gt;// and to AsyncEnumerator&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            asyncEnum.DequeueAsyncResult(); &lt;span style="color: #008000"&gt;// we don't need this&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        });&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; 1;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    };&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Note that we make use of a handy feature of &lt;strong&gt;AsyncEnumerator&lt;/strong&gt; where we stash the exception inside it by calling Cancel. We then continue as normal, calling on to &lt;strong&gt;AsyncEnumerator&lt;/strong&gt;’s callback, which means that the iteration will resume. What does this mean?&lt;/p&gt;

&lt;p&gt;It means that when iteration resumes, the first thing we need to check for the cancellation, retrieve the exception and throw it. Unfortunately, this means we need to mess up our nice simple &lt;strong&gt;Execute&lt;/strong&gt; function. If you refer to where I defined it above, you’ll see that I originally used &lt;strong&gt;Select&lt;/strong&gt; to do all the looping and yielding. But this doesn’t allow us to perform the exception check immediately after resuming from the yield return. We need to write out the equivalent of Select in “long hand” so we can insert the extra code:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Execute(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt; AsyncEnumerator asyncEnum, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                           IEnumerable&amp;lt;Activity&amp;gt; activities)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    asyncEnum.Execute(AdaptEnumerator(asyncEnum, activities));&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;}&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; IEnumerator&amp;lt;&lt;span style="color: #0000ff"&gt;int&lt;/span&gt;&amp;gt; AdaptEnumerator(&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;       AsyncEnumerator asyncEnum, Enumerable&amp;lt;Activity&amp;gt; activities)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (Activity activity &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; activities)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; activity(asyncEnum);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;object&lt;/span&gt; x;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (asyncEnum.IsCanceled(&lt;span style="color: #0000ff"&gt;out&lt;/span&gt; x) &amp;amp;&amp;amp; (x &lt;span style="color: #0000ff"&gt;is&lt;/span&gt; Exception))&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            &lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; (Exception)x;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The private &lt;strong&gt;AdaptEnumerator&lt;/strong&gt; function serves as the equivalent of &lt;strong&gt;Select&lt;/strong&gt;, except that it checks for an exception to throw immediately following resumption after the yield return. This means that after the asynchronous action completes with an error, no further code executes in the underlying function that yields the Activities.&lt;/p&gt;

&lt;p&gt;Like I say, I have only written this and done the above analysis on it, not really tested much. If you want to give it a try, be my guest:&lt;/p&gt;

&lt;p&gt;&lt;a title="http://www.earwicker.com/downloads/async.zip" href="http://www.earwicker.com/downloads/async.zip"&gt;http://www.earwicker.com/downloads/async.zip&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Please let me know if you find any ridiculous bugs or design flaws, or even if it works. It’s just a source file containing all the functions (just 150 or so lines of code), so it could be added to any project already using &lt;strong&gt;AsyncEnumerator&lt;/strong&gt;, or built into a separate class library.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-4970907164211815174?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/4970907164211815174/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=4970907164211815174' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/4970907164211815174'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/4970907164211815174'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2008/12/more-on-jeffrey-richters.html' title='More on Jeffrey Richter’s AsyncEnumerator and Functional Programming'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-4024840671764308392</id><published>2008-12-05T14:13:00.002Z</published><updated>2011-02-04T17:12:33.535Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambdas'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='yield return'/><title type='text'>Asynchronous Sockets with Yield Return of Lambdas</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2008/12/05/asynchronous-sockets-with-yield-return-of-lambdas/'&lt;/script&gt;

&lt;p&gt;&lt;strong&gt;Update: &lt;/strong&gt;&lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2008/12/more-on-jeffrey-richters.html"&gt;&lt;strong&gt;More in-depth stuff about this&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;I just watched this video of Jeffrey Richter demonstrating his AsyncEnumerator class:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://channel9.msdn.com/posts/Charles/Jeffrey-Richter-and-his-AsyncEnumerator"&gt;http://channel9.msdn.com/posts/Charles/Jeffrey-Richter-and-his-AsyncEnumerator&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The key idea is the realisation that yield return takes care of turning a single function into a continuation that can be resumed under the control of some other code, but still provides a natural way to write procedurally. This is just what is needed to manage asynchronous communication. Great stuff.&lt;/p&gt;  &lt;p&gt;But I had an idea while watching it. His code seems to still place some burden on the caller to know about the details of asynchronous socket programming - how to specify a callback, etc.&lt;/p&gt;  &lt;p&gt;Instead, why not hide those details. The trick is to use &lt;strong&gt;yield return&lt;/strong&gt; to pass back lambda expressions containing the work to do asynchronously.&lt;/p&gt;  &lt;p&gt;Here's a quick sample - look at this first, to see how easy it is to use. It's important you see that first, because unless you're into functional programming, the behind-the-scenes stuff may seem confusing.&lt;/p&gt;  &lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;   &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;     &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #008000"&gt;/* Trivial example of a protocol - send a byte containing the payload&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #008000"&gt; * length, followed by that many bytes of data.&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #008000"&gt; * &lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #008000"&gt; * This server just sends back the same data in the same way.&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #008000"&gt; */&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;static&lt;/span&gt; IEnumerable&amp;lt;AsyncIOPipeAction&amp;gt; HandleMyClient()&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #008000"&gt;// Start by reading a byte from the client&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[] singleByte = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; &lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[1];&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    yield &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; pipe =&amp;gt; pipe.Read(singleByte, 0, 1);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #008000"&gt;// That byte tells us how much to read next&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; inputPayloadLength = singleByte[0];&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[] inputPayload = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; &lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[inputPayloadLength];&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    yield &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; pipe =&amp;gt; pipe.Read(inputPayload, 0, inputPayloadLength);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #008000"&gt;// Send same thing back again&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    yield &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; pipe =&amp;gt; pipe.Write(singleByte, 0, 1);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    yield &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; pipe =&amp;gt; pipe.Write(inputPayload, 0, inputPayloadLength);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;As you can see, this function doesn't actually get passed a socket to work on. And yet it has these suspiciously convenient-looking calls on to a &lt;strong&gt;pipe&lt;/strong&gt; object. Where does that &lt;strong&gt;pipe&lt;/strong&gt; object come from and what is it?&lt;/p&gt;

&lt;p&gt;Note how the whole function returns &lt;strong&gt;IEnumerable&amp;lt;AsyncIOPipeAction&amp;gt;&lt;/strong&gt;, so it produces actions to be called somehow. Those actions are delegates:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;delegate&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; AsyncIOPipeAction(IAsyncIOPipe pipe);&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;That &lt;strong&gt;pipe&lt;/strong&gt; object supports this interface:&lt;/p&gt;

&lt;div&gt;
  &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&lt;span style="color: #008000"&gt;/* Example of an interface with operations that are either synchronous &lt;/span&gt;
&lt;span style="color: #008000"&gt; * or asynchronous depending on the context in which they are called.&lt;/span&gt;
&lt;span style="color: #008000"&gt; */&lt;/span&gt; 
&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;interface&lt;/span&gt; IAsyncIOPipe
{
    &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Read(&lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[] buffer, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; offset, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; size);
    &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Write(&lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[] buffer, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; offset, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; size);
}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;You could follow the same pattern with any facility that supports asynchronous usage, but here I just provide two obvious operations on a socket.&lt;/p&gt;

&lt;p&gt;So in the client-handling function, whenever you want to make use of the socket, you do a &lt;strong&gt;yield return&lt;/strong&gt; to hand off some code that can be called back to. Your code must accept a pipe (which is just what you wanted). Then it can call a method on it.&lt;/p&gt;

&lt;p&gt;The implementation &lt;strong&gt;IAsyncIOPipe&lt;/strong&gt; is then very simple indeed:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; SocketPipe : IAsyncIOPipe&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;readonly&lt;/span&gt; Socket _socket;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;readonly&lt;/span&gt; IEnumerator&amp;lt;AsyncIOPipeAction&amp;gt; _actions;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; SocketPipe(Socket socket, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;                      IEnumerable&amp;lt;AsyncIOPipeAction&amp;gt; actions)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        _socket = socket;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        _actions = actions.GetEnumerator();&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        Step();&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Step()&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (!_actions.MoveNext())&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;            &lt;span style="color: #0000ff"&gt;return&lt;/span&gt;;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        _actions.Current(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Callback(IAsyncResult result)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        _socket.EndReceive(result);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        Step();&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Read(&lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[] buffer, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; offset, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; size)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        _socket.BeginReceive(buffer, offset, size, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                             SocketFlags.None, Callback, &lt;span style="color: #0000ff"&gt;this&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;&amp;#160;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Write(&lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[] buffer, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; offset, &lt;span style="color: #0000ff"&gt;int&lt;/span&gt; size)&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;    {&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;        _socket.BeginSend(buffer, offset, size, &lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;                          SocketFlags.None, Callback, &lt;span style="color: #0000ff"&gt;this&lt;/span&gt;);&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    }&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The constructor is passed a bunch of actions to be carried out asynchronously. It doesn't actually care how that collection of actions is implemented. But of course we can call &lt;strong&gt;HandleMyClient&lt;/strong&gt; to produce a suitable collection.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SocketPipe&lt;/strong&gt; starts the ball rolling immediately, by starting the enumeration and then calling &lt;strong&gt;Step&lt;/strong&gt;. This executes the first portion of code in the function up to the first &lt;strong&gt;yield return&lt;/strong&gt;, after which we get control back. We then just execute the lambda giving it a pipe to work on - our implementation, in fact.&lt;/p&gt;

&lt;p&gt;This means that when the lambda calls &lt;strong&gt;Read&lt;/strong&gt; or &lt;strong&gt;Write&lt;/strong&gt;, we can simply begin the right kind of asynchronous operation on our concealed socket, and we take care of specifying the callback. All our callback has to do is end the asynchronous operation and run the next &lt;strong&gt;Step&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Exercises for the reader:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;There isn't much consideration given to error handling, mainly because I never even looked at the asynchronous socket APIs until just now, so I'm not sure where it needs to go. It should be possible to put error handling into this approach without putting any mess in the application code (e.g. &lt;strong&gt;HandleMyClient&lt;/strong&gt;). &lt;/li&gt;

  &lt;li&gt;It should be possible to launch multiple asynchronous calls on multiple objects, where that makes sense (I can't see how it does in this simple example, but it might if you have multiple sockets for some reason). The lambda would need to be passed multiple parameters, one for each object currently &amp;quot;in play&amp;quot;, and the management object would need to ensure that all outstanding asynchronous calls had completed before it called &lt;strong&gt;Step&lt;/strong&gt; again. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Solution zip file is here:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.earwicker.com/downloads/asyncsockets.zip"&gt;http://www.earwicker.com/downloads/asyncsockets.zip&lt;/a&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-4024840671764308392?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/4024840671764308392/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=4024840671764308392' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/4024840671764308392'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/4024840671764308392'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2008/12/asynchronous-sockets-with-yield-return.html' title='Asynchronous Sockets with Yield Return of Lambdas'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-5818852460276744361</id><published>2008-11-19T14:58:00.002Z</published><updated>2011-02-04T17:13:47.079Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='DSLs'/><category scheme='http://www.blogger.com/atom/ns#' term='COIL'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><title type='text'>COIL and COILettes</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2008/11/19/coil-and-coilettes/'&lt;/script&gt;

&lt;p&gt;&lt;a href="http://www.crockford.com/"&gt;Douglas Crockford&lt;/a&gt; started a &lt;a href="http://blogs.msdn.com/mikechampion/archive/2006/12/21/the-json-vs-xml-debate-begins-in-earnest.aspx"&gt;minor war&lt;/a&gt; when he observed that JavaScript's object initialisation syntax provides a neat way to persist hierarchical data, maybe more suitable to some situations than XML.&lt;/p&gt;  &lt;p&gt;Since C# 3.0 we've had a similar facility in C#. This means an opportunity for another war.&lt;/p&gt;  &lt;p&gt;I've started to see little object initialisation trees appearing in my code, and they start to look like a declarative internal DSL. I should post a real example some time. Anyway, this can only mean one thing: we need a snappy name for these things.&lt;/p&gt;  &lt;p&gt;JSON stands for JavaScript Object Notation, and it sounds sort of like the name Jason, which makes it catchy. So we need a four letter acronym that starts with CS (for C-Sharp) where you pronounce the first letter as a syllable and it all sounds like a person's name. This immediately lead me to:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;strong&gt;CSIL&lt;/strong&gt; (pronounced &amp;quot;Cecil&amp;quot; in the American way):&lt;/p&gt;    &lt;p&gt;&lt;strong&gt;C&lt;/strong&gt;-&lt;strong&gt;S&lt;/strong&gt;harp &lt;strong&gt;I&lt;/strong&gt;nitialisation &lt;strong&gt;L&lt;/strong&gt;anguage.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Sadly &lt;a href="http://sourceforge.net/projects/csil/"&gt;somebody already used that for something else&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Ah well, it was just too perfect.&lt;/p&gt;  &lt;p&gt;But not to be discouraged, I relaxed the rules so it just has to be a four letter acronym that sounds like a word, and went for:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;strong&gt;COIL&lt;/strong&gt; (pronounced &amp;quot;coil&amp;quot;, amazingly):&lt;/p&gt;    &lt;p&gt;&lt;strong&gt;C&lt;/strong&gt;# &lt;strong&gt;O&lt;/strong&gt;bject &lt;strong&gt;I&lt;/strong&gt;nitialisation &lt;strong&gt;L&lt;/strong&gt;anguage.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The beauty of this becomes apparent when you consider that we also need a way to describe those little islands of COIL that appear embedded in our C# programs.&lt;/p&gt;  &lt;p&gt;They are called &lt;a href="http://en.wikipedia.org/wiki/Bend_Her"&gt;COILettes&lt;/a&gt;.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8715120618224381002-5818852460276744361?l=incrediblejourneysintotheknown.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://incrediblejourneysintotheknown.blogspot.com/feeds/5818852460276744361/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8715120618224381002&amp;postID=5818852460276744361' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/5818852460276744361'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8715120618224381002/posts/default/5818852460276744361'/><link rel='alternate' type='text/html' href='http://incrediblejourneysintotheknown.blogspot.com/2008/11/coil-and-coilettes.html' title='COIL and COILettes'/><author><name>Daniel Earwicker</name><uri>http://www.blogger.com/profile/11384619047799752406</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_vT-uiJGZY5w/SY_6QUORJVI/AAAAAAAAAFE/KHD0V6fgBjo/S220/cupT.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8715120618224381002.post-430215062223068394</id><published>2008-11-13T10:42:00.002Z</published><updated>2011-02-04T17:14:35.725Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='wish'/><category scheme='http://www.blogger.com/atom/ns#' term='C#'/><category scheme='http://www.blogger.com/atom/ns#' term='LINQ'/><category scheme='http://www.blogger.com/atom/ns#' term='BCL'/><title type='text'>Chain – a LINQ operator for dealing with Linked Lists</title><content type='html'>&lt;script&gt;location = 'http://smellegantcode.wordpress.com/2008/11/13/chain-%E2%80%93-a-linq-operator-for-dealing-with-linked-lists/'&lt;/script&gt;

&lt;p&gt;I don’t think there’s anything in LINQ that will do this, though I expect I’m wrong - I have a tendency to write my own extension method to do something and then discover that LINQ already provides a general version of it. But in the mean time, here’s my Chain method:&lt;/p&gt;  &lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;   &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;     &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; Chain&amp;lt;T&amp;gt;(&lt;span style="color: #0000ff"&gt;this&lt;/span&gt; T first, Func&amp;lt;T, T&amp;gt; follow) &lt;span style="color: #0000ff"&gt;where&lt;/span&gt; T : &lt;span style="color: #0000ff"&gt;class&lt;/span&gt;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;{&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;    &lt;span style="color: #0000ff"&gt;for&lt;/span&gt; (T item = first; item != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;; item = follow(item))&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;        &lt;span style="color: #0000ff"&gt;yield&lt;/span&gt; &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; item;&lt;/pre&gt;

    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: white; border-bottom-style: none"&gt;}&lt;/pre&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;It’s designed to be used in any situation where a traditional linked list exists. I used it in my &lt;a href="http://incrediblejourneysintotheknown.blogspot.com/2008/11/autodisposal-using-postsharp.html"&gt;AutoDisposal library&lt;/a&gt; to get a list of all the types inherited by a given type. It chains a bunch of objects together into an enumerable list by following links between them.&lt;/p&gt;

&lt;p&gt;The irritation that provoked this minor burst of creativity is that if you use the GetFields method of Type, there doesn’t seem to be a simple way to get all the instance fields in that type, including inherited ones. By default, GetFields does include inherited fields, &lt;em&gt;but only public ones&lt;/em&gt;. To get all public and non-public instance fields, including all inherited ones, you have to walk the chain of base types and get the fields declared in each type. So you’d better use BindingFlags.DeclaredOnly, or you’ll end up with duplicates of the public fields.&lt;/p&gt;

&lt;p&gt;I wanted to write a LINQ expression that would get me a single flat list of all the fields in a type, so this is how I used Chain as part of it:&lt;/p&gt;

&lt;div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; background-color: #f4f4f4; max-height: 200px"&gt;
  &lt;div style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &amp;#39;Courier New&amp;#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"&gt;
    &lt;pre style="padding-right: 0px; padding-left: 0px; font-size
