<?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-1562048197280495196</id><updated>2011-07-07T22:39:52.879-03:00</updated><category term='Personal'/><category term='Reflection'/><category term='Yield'/><category term='Performance'/><category term='Linq'/><category term='IEnumerable'/><category term='Template Method'/><category term='Value Types'/><category term='MSDN Forums'/><category term='CIL'/><category term='Variance'/><category term='Fun'/><category term='Forums Browser'/><category term='C# 4.0'/><title type='text'>Keep It Sharp</title><subtitle type='html'>Fernando Nicolet's thoughts and experiences with C#.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://fernandonicolet.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://fernandonicolet.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Fernando Nicolet</name><uri>http://www.blogger.com/profile/04402615396818391251</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='27' height='32' src='http://3.bp.blogspot.com/_mmG4Sk1Z5oY/SgTqce9blEI/AAAAAAAAAAY/IazFgTXhp0U/S220/profile.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>8</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-1562048197280495196.post-3872670520500985415</id><published>2009-09-22T19:19:00.000-03:00</published><updated>2009-09-22T19:20:25.065-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Personal'/><title type='text'>New Job, New Challenges</title><content type='html'>&lt;p&gt;I haven’t been blogging lately, but hopefully I will start getting the ball rolling once again. Let’s start with a personal post.&lt;/p&gt;
&lt;p&gt;Yesterday I started on a new job at &lt;a href="http://www.intermedia.com.uy"&gt;Intermedia&lt;/a&gt;, and I can’t stress enough how happy this makes me. I can’t wait to face all the new challenges that will arise through time, and my co-workers managed to make me feel very comfortable in only two days. I’m sure I’ll get to know really great people and very talented developers from which I will learn a lot. Also, this company has very interesting projects which most involve state of the art technology.&lt;/p&gt;
&lt;p&gt;One of my main tasks will be research, which hopefully will have a positive impact on this blog. I hope you’ll enjoy what’s coming.&lt;/p&gt;
&lt;p&gt;The board is set, let’s get it on!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1562048197280495196-3872670520500985415?l=fernandonicolet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fernandonicolet.blogspot.com/feeds/3872670520500985415/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fernandonicolet.blogspot.com/2009/09/new-job-new-challenges.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/3872670520500985415'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/3872670520500985415'/><link rel='alternate' type='text/html' href='http://fernandonicolet.blogspot.com/2009/09/new-job-new-challenges.html' title='New Job, New Challenges'/><author><name>Fernando Nicolet</name><uri>http://www.blogger.com/profile/04402615396818391251</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='27' height='32' src='http://3.bp.blogspot.com/_mmG4Sk1Z5oY/SgTqce9blEI/AAAAAAAAAAY/IazFgTXhp0U/S220/profile.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1562048197280495196.post-2101557006924145014</id><published>2009-06-27T23:18:00.007-03:00</published><updated>2009-07-12T17:42:29.075-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Yield'/><category scheme='http://www.blogger.com/atom/ns#' term='IEnumerable'/><category scheme='http://www.blogger.com/atom/ns#' term='Template Method'/><category scheme='http://www.blogger.com/atom/ns#' term='Linq'/><category scheme='http://www.blogger.com/atom/ns#' term='Variance'/><title type='text'>Template Method Pattern &amp; IEnumerable</title><content type='html'>&lt;h5&gt;An Analysis Through C#'s Evolution&lt;/h5&gt;
&lt;p&gt;The &lt;a href="http://www.dofactory.com/Patterns/PatternTemplate.aspx"&gt;template method&lt;/a&gt; is a very useful pattern commonly used within Data Access Layers. It's one of the simplest patterns within the gang of four, very similar to &lt;a href="http://www.dofactory.com/Patterns/PatternCommand.aspx"&gt;Command&lt;/a&gt; and &lt;a href="http://www.dofactory.com/Patterns/PatternStrategy.aspx"&gt;Strategy&lt;/a&gt; and also belongs to the behavioral patterns. It makes good use of polymorphism in a simple class hierarchy.&lt;/p&gt;
&lt;img src="http://ygjpyg.blu.livefilestore.com/y1pm4rt6KE5IonlSqQ6LYI5gAYsCENuBC-OE-9HC7dvrhEAZxvHBoBPDH9zyBBnTnRdXFDT5GIy5yMq3h24-fwcD2qEWSLlaFxX/template_method_uml.png" alt="Template Method's UML" title="Template Method's UML" /&gt;
&lt;p&gt;&lt;span class="i"&gt;Diagram copied from &lt;a href="http://www.dofactory.com/Patterns/Patterns.aspx"&gt;data &amp;amp; object factory&lt;/a&gt;.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;A template method defines the skeleton of an algorithm delegating specific operations in it to subclasses. Whenever a process within an object is very similar between different siblings, then a Template Method is a candidate. I don't want to bore you with the details so I'll dig right into some code.&lt;/p&gt;
&lt;p&gt;Consider the following abstract class for games:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected abstract void&lt;/span&gt; InitializeGame();
&lt;span class="keyword"&gt;protected abstract &lt;/span&gt;&lt;span class="type"&gt;ArrayList&lt;/span&gt; GetPlayers();
&lt;span class="keyword"&gt;protected abstract void&lt;/span&gt; MakeMove(&lt;span class="type"&gt;Player&lt;/span&gt; player);
&lt;span class="keyword"&gt;protected abstract bool&lt;/span&gt; GameEnded { &lt;span class="keyword"&gt;get&lt;/span&gt;; }
&lt;span class="keyword"&gt;protected abstract void&lt;/span&gt; DisplayResults();

&lt;span class="keyword"&gt;public void&lt;/span&gt; Play()

    InitializeGame();
    &lt;span class="keyword"&gt;while&lt;/span&gt; (!GameEnded)
    {
        &lt;span class="keyword"&gt;foreach&lt;/span&gt; (&lt;span class="type"&gt;Player&lt;/span&gt; player &lt;span class="keyword"&gt;in&lt;/span&gt; GetPlayers())
        {
            MakeMove(player);
        }
    }
    DisplayResults();
}&lt;/pre&gt;
&lt;p&gt;And a simple &lt;span class="codesample"&gt;Player&lt;/span&gt; class:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;Player&lt;/span&gt;
{
    &lt;span class="keyword"&gt;private readonly string&lt;/span&gt; name;

    &lt;span class="keyword"&gt;public string&lt;/span&gt; Name
    {
        &lt;span class="keyword"&gt;get&lt;/span&gt; { &lt;span class="keyword"&gt;return this&lt;/span&gt;.name; }
    }

    &lt;span class="keyword"&gt;public&lt;/span&gt; Player(&lt;span class="keyword"&gt;string&lt;/span&gt; name)
    {
        &lt;span class="keyword"&gt;this&lt;/span&gt;.name = name;
    }

    &lt;span class="keyword"&gt;public override bool&lt;/span&gt; Equals(&lt;span class="keyword"&gt;object&lt;/span&gt; obj)
    {
        &lt;span class="type"&gt;Player&lt;/span&gt; player = obj &lt;span class="keyword"&gt;as &lt;/span&gt;&lt;span class="type"&gt;Player&lt;/span&gt;;
        &lt;span class="keyword"&gt;return&lt;/span&gt; (player != &lt;span class="keyword"&gt;null&lt;/span&gt;) &amp;amp;&amp;amp; &lt;span class="keyword"&gt;object&lt;/span&gt;.Equals(&lt;span class="keyword"&gt;this&lt;/span&gt;.Name, player.Name);
    }

    &lt;span class="keyword"&gt;public override int&lt;/span&gt; GetHashCode()
    {
        &lt;span class="keyword"&gt;return this&lt;/span&gt;.Name == &lt;span class="keyword"&gt;null&lt;/span&gt; ? 0 : &lt;span class="keyword"&gt;this&lt;/span&gt;.Name.GetHashCode() * 53;
    }

}&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;Play&lt;/code&gt; method is a Template Method, wherein &lt;code&gt;InitializeGame&lt;/code&gt;, &lt;code&gt;GetPlayers&lt;/code&gt;, &lt;code&gt;MakeMove&lt;/code&gt;, &lt;code&gt;GameEnded&lt;/code&gt; and &lt;code&gt;DisplayResult &lt;/code&gt;are Primitive Operations.&lt;/p&gt;
&lt;p&gt;Here's a basic implementation of a High Card game:&lt;/p&gt;
&lt;pre style="height: 200px"&gt;&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;HighCard&lt;/span&gt; : &lt;span class="type"&gt;GameBase&lt;/span&gt;
{

    &lt;span class="keyword"&gt;private int&lt;/span&gt; rounds;
    &lt;span class="keyword"&gt;private &lt;/span&gt;&lt;span class="type"&gt;ArrayList&lt;/span&gt; players;
    &lt;span class="keyword"&gt;private int&lt;/span&gt; currentRound;
    &lt;span class="keyword"&gt;private &lt;/span&gt;&lt;span class="type"&gt;Random&lt;/span&gt; random;
    &lt;span class="keyword"&gt;private &lt;/span&gt;&lt;span class="type"&gt;Card&lt;/span&gt;[] currentHand;

    &lt;span class="keyword"&gt;public&lt;/span&gt; HighCard()
    {
        players = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;ArrayList&lt;/span&gt;();
        random = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;Random&lt;/span&gt;();
    }

    &lt;span class="keyword"&gt;protected override void&lt;/span&gt; InitializeGame()
    {
        players.Clear();
        currentRound = 0;
        &lt;span class="type"&gt;Hashtable&lt;/span&gt; names = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;Hashtable&lt;/span&gt;();
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;-------------------------------------------------------------------------&amp;quot;&lt;/span&gt;);
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot; Welcome to the Increbile High Card game. Please buckle your seat belts.&amp;quot;&lt;/span&gt;);
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;-------------------------------------------------------------------------&amp;quot;&lt;/span&gt;);
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine();
        &lt;span class="keyword"&gt;bool&lt;/span&gt; keepAsking = &lt;span class="keyword"&gt;true&lt;/span&gt;;
        &lt;span class="keyword"&gt;while&lt;/span&gt; (keepAsking)
        {
            &lt;span class="keyword"&gt;if&lt;/span&gt; (players.Count &amp;lt; 2)
            {
                &lt;span class="type"&gt;Console&lt;/span&gt;.Write(&lt;span class="string"&gt;&amp;quot;Enter player's name: &amp;quot;&lt;/span&gt;);
            }
            &lt;span class="keyword"&gt;else&lt;/span&gt;
            {
                &lt;span class="type"&gt;Console&lt;/span&gt;.Write(&lt;span class="string"&gt;&amp;quot;Enter player's name (leave blank for no more players): &amp;quot;&lt;/span&gt;);
            }
            &lt;span class="keyword"&gt;string&lt;/span&gt; playerName = &lt;span class="type"&gt;Console&lt;/span&gt;.ReadLine();
            &lt;span class="keyword"&gt;if&lt;/span&gt; (playerName.Length &amp;gt; 0)
            {
                &lt;span class="keyword"&gt;if&lt;/span&gt; (names.ContainsKey(playerName))
                {
                    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;I'm sorry, but we already have a contestant named {0}.&amp;quot;&lt;/span&gt;, playerName);
                }
                &lt;span class="keyword"&gt;else&lt;/span&gt;
                {
                    &lt;span class="type"&gt;Player&lt;/span&gt; player = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;HighCardPlayer&lt;/span&gt;(playerName);
                    players.Add(player);
                    names.Add(playerName, &lt;span class="keyword"&gt;null&lt;/span&gt;);
                }
            }
            &lt;span class="keyword"&gt;else&lt;/span&gt;
            {
                &lt;span class="keyword"&gt;if&lt;/span&gt; (players.Count &amp;gt;= 2)
                {
                    keepAsking = &lt;span class="keyword"&gt;false&lt;/span&gt;;
                }
            }
        }
        currentHand = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;Card&lt;/span&gt;[players.Count];
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine();
        &lt;span class="type"&gt;Console&lt;/span&gt;.Write(&lt;span class="string"&gt;&amp;quot;How many rounds would you like to play? &amp;quot;&lt;/span&gt;);
        &lt;span class="keyword"&gt;while&lt;/span&gt; (!&lt;span class="keyword"&gt;int&lt;/span&gt;.TryParse(&lt;span class="type"&gt;Console&lt;/span&gt;.ReadLine(), &lt;span class="keyword"&gt;out&lt;/span&gt; rounds))
        {
            &lt;span class="type"&gt;Console&lt;/span&gt;.Write(&lt;span class="string"&gt;&amp;quot;I'm sorry, I don't understand what you mean by that. How many rounds? &amp;quot;&lt;/span&gt;);
        }
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine();
    }

    &lt;span class="keyword"&gt;protected override &lt;/span&gt;&lt;span class="type"&gt;ArrayList&lt;/span&gt; GetPlayers()
    {
        &lt;span class="keyword"&gt;return&lt;/span&gt; players;
    }

    &lt;span class="keyword"&gt;protected override void&lt;/span&gt; MakeMove(&lt;span class="type"&gt;Player&lt;/span&gt; player)
    {
        &lt;span class="keyword"&gt;int&lt;/span&gt; playerIndex = players.IndexOf(player);

        &lt;span class="type"&gt;Console&lt;/span&gt;.Write(&lt;span class="string"&gt;&amp;quot;{0} gets the... &amp;quot;&lt;/span&gt;, player.Name);
        &lt;span class="type"&gt;Thread&lt;/span&gt;.Sleep(random.Next(500, 1000));

        &lt;span class="type"&gt;Card&lt;/span&gt; card = GetNewCard();

        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;{0} of {1}&amp;quot;&lt;/span&gt;, card.Value, card.Suit);
        currentHand[playerIndex] = card;

        &lt;span class="keyword"&gt;if&lt;/span&gt; (playerIndex == players.Count - 1)
        {
            EvaluateRound();
        }
    }

    &lt;span class="keyword"&gt;protected override bool&lt;/span&gt; GameEnded
    {
        &lt;span class="keyword"&gt;get &lt;/span&gt;
        { 
            &lt;span class="keyword"&gt;return&lt;/span&gt; rounds == currentRound; 
        }
    }

    &lt;span class="keyword"&gt;protected override void&lt;/span&gt; DisplayResults()
    {
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;GAME OVER&amp;quot;&lt;/span&gt;);
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine();
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;Final Scores:&amp;quot;&lt;/span&gt;);

        &lt;span class="type"&gt;ArrayList&lt;/span&gt; winners = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;ArrayList&lt;/span&gt;();
        &lt;span class="keyword"&gt;int&lt;/span&gt; winnerScore = &lt;span class="keyword"&gt;int&lt;/span&gt;.MinValue;
        &lt;span class="keyword"&gt;for&lt;/span&gt; (&lt;span class="keyword"&gt;int&lt;/span&gt; i = 0; i &amp;lt; players.Count; i++)
        {
            &lt;span class="type"&gt;HighCardPlayer&lt;/span&gt; player = (&lt;span class="type"&gt;HighCardPlayer&lt;/span&gt;)players[i];
            &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;* {0}: {1} points&amp;quot;&lt;/span&gt;, player.Name, player.Score);
            &lt;span class="keyword"&gt;if&lt;/span&gt; (player.Score &amp;gt; winnerScore)
            {
                winnerScore = player.Score;
                winners.Clear();
                winners.Add (player);
            }
            &lt;span class="keyword"&gt;else if&lt;/span&gt; (player.Score == winnerScore)
            {
                winners.Add (player);
            }
        }
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine();
        &lt;span class="keyword"&gt;if&lt;/span&gt; (winners.Count != players.Count)
        {
            &lt;span class="keyword"&gt;if&lt;/span&gt; (winners.Count == 1)
            {
                &lt;span class="type"&gt;Console&lt;/span&gt;.Write(&lt;span class="string"&gt;&amp;quot;And the winner is: &amp;quot;&lt;/span&gt;);
            }
            &lt;span class="keyword"&gt;else&lt;/span&gt;
            {
                &lt;span class="type"&gt;Console&lt;/span&gt;.Write(&lt;span class="string"&gt;&amp;quot;And the winners are: &amp;quot;&lt;/span&gt;);
            }
            &lt;span class="type"&gt;Console&lt;/span&gt;.ForegroundColor = &lt;span class="type"&gt;ConsoleColor&lt;/span&gt;.White;
            &lt;span class="type"&gt;Console&lt;/span&gt;.Write(((&lt;span class="type"&gt;Player&lt;/span&gt;)winners[0]).Name.ToUpper());
            &lt;span class="keyword"&gt;for&lt;/span&gt; (&lt;span class="keyword"&gt;int&lt;/span&gt; i = 1; i &amp;lt; winners.Count; i++)
            {
                &lt;span class="type"&gt;Console&lt;/span&gt;.Write(&lt;span class="string"&gt;&amp;quot; - {0}&amp;quot;&lt;/span&gt;, ((&lt;span class="type"&gt;Player&lt;/span&gt;)winners[i]).Name.ToUpper());
            }
            &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine();
            &lt;span class="type"&gt;Console&lt;/span&gt;.ForegroundColor = &lt;span class="type"&gt;ConsoleColor&lt;/span&gt;.Gray;
        }
        &lt;span class="keyword"&gt;else&lt;/span&gt;
        {
            &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;There are NO winners! It's an all tie!&amp;quot;&lt;/span&gt;);
        }
    }

    &lt;span class="keyword"&gt;private &lt;/span&gt;&lt;span class="type"&gt;Card&lt;/span&gt; GetNewCard()
    {
        &lt;span class="type"&gt;Card&lt;/span&gt; card = &lt;span class="keyword"&gt;null&lt;/span&gt;;
        &lt;span class="keyword"&gt;do&lt;/span&gt;
        {
            card = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;Card&lt;/span&gt;(random.Next(1, 14), random.Next(1, 5));
        } &lt;span class="keyword"&gt;while&lt;/span&gt; (CardIsInHand(card));

        &lt;span class="keyword"&gt;return&lt;/span&gt; card;
    }

    &lt;span class="keyword"&gt;private bool&lt;/span&gt; CardIsInHand(&lt;span class="type"&gt;Card&lt;/span&gt; card)
    {
        &lt;span class="keyword"&gt;for&lt;/span&gt; (&lt;span class="keyword"&gt;int&lt;/span&gt; i = 0; i &amp;lt; currentHand.Length; i++)
        {
            &lt;span class="keyword"&gt;if&lt;/span&gt; (card.Equals(currentHand[i]))
            {
                &lt;span class="keyword"&gt;return true&lt;/span&gt;;
            }
        }
        &lt;span class="keyword"&gt;return false&lt;/span&gt;;
    }

    &lt;span class="keyword"&gt;private void&lt;/span&gt; EvaluateRound()
    {
        currentRound++;
        &lt;span class="type"&gt;HighCardPlayer&lt;/span&gt; player = GetRoundsWinner();
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine();
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;Congratulations {0}! You won this round!&amp;quot;&lt;/span&gt;, player.Name);
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine();
        player.Score++;
        ClearHand();
    }

    &lt;span class="keyword"&gt;private &lt;/span&gt;&lt;span class="type"&gt;HighCardPlayer&lt;/span&gt; GetRoundsWinner()
    {
        &lt;span class="keyword"&gt;int&lt;/span&gt; winnerIndex = 0;
        &lt;span class="keyword"&gt;for&lt;/span&gt; (&lt;span class="keyword"&gt;int&lt;/span&gt; i = 1; i &amp;lt; currentHand.Length; i++)
        {
            &lt;span class="keyword"&gt;if&lt;/span&gt; (currentHand[i].CompareTo(currentHand[winnerIndex]) &amp;gt; 0)
            {
                winnerIndex = i;
            }
        }
        &lt;span class="keyword"&gt;return&lt;/span&gt; (&lt;span class="type"&gt;HighCardPlayer&lt;/span&gt;)players[winnerIndex];
    }

    &lt;span class="keyword"&gt;private void&lt;/span&gt; ClearHand()
    {
        &lt;span class="keyword"&gt;for&lt;/span&gt; (&lt;span class="keyword"&gt;int&lt;/span&gt; i = 0; i &amp;lt; currentHand.Length; i++)
        {
            currentHand[i] = &lt;span class="keyword"&gt;null&lt;/span&gt;;
        }
    }

}

&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;Card&lt;/span&gt;: &lt;span class="type"&gt;IComparable&lt;/span&gt;
{

    &lt;span class="keyword"&gt;int&lt;/span&gt; valueIndex;
    &lt;span class="keyword"&gt;int&lt;/span&gt; suitIndex;

    &lt;span class="keyword"&gt;private static string&lt;/span&gt;[] suits = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;String&lt;/span&gt;[] { &lt;span class="string"&gt;&amp;quot;Clubs&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;Diamonds&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;Hearts&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;Spades&amp;quot;&lt;/span&gt; };
    &lt;span class="keyword"&gt;private string&lt;/span&gt;[] values = &lt;span class="keyword"&gt;new string&lt;/span&gt;[] { &lt;span class="string"&gt;&amp;quot;2&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;3&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;4&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;5&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;6&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;7&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;8&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;9&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;10&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;J&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;Q&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;K&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;A&amp;quot;&lt;/span&gt; };

    &lt;span class="keyword"&gt;public&lt;/span&gt; Card(&lt;span class="keyword"&gt;int&lt;/span&gt; value, &lt;span class="keyword"&gt;int&lt;/span&gt; suit)
    {
        &lt;span class="keyword"&gt;if&lt;/span&gt; ((value &amp;lt; 1) || (value &amp;gt; 13)) &lt;span class="keyword"&gt;throw new &lt;/span&gt;&lt;span class="type"&gt;ArgumentOutOfRangeException&lt;/span&gt;(&lt;span class="string"&gt;&amp;quot;value&amp;quot;&lt;/span&gt;);
        &lt;span class="keyword"&gt;if&lt;/span&gt; ((suit &amp;lt; 1) || (suit &amp;gt; 4)) &lt;span class="keyword"&gt;throw new &lt;/span&gt;&lt;span class="type"&gt;ArgumentOutOfRangeException&lt;/span&gt;(&lt;span class="string"&gt;&amp;quot;suit&amp;quot;&lt;/span&gt;);

        &lt;span class="keyword"&gt;this&lt;/span&gt;.suitIndex = suit - 1;
        &lt;span class="keyword"&gt;if&lt;/span&gt; (value == 1)
        {
            &lt;span class="keyword"&gt;this&lt;/span&gt;.valueIndex = 12;
        }
        &lt;span class="keyword"&gt;else&lt;/span&gt;
        {
            &lt;span class="keyword"&gt;this&lt;/span&gt;.valueIndex = value - 2;
        }
    }

    &lt;span class="keyword"&gt;public string&lt;/span&gt; Value
    {
        &lt;span class="keyword"&gt;get&lt;/span&gt; { &lt;span class="keyword"&gt;return&lt;/span&gt; values[valueIndex]; }
    }

    &lt;span class="keyword"&gt;public string&lt;/span&gt; Suit
    {
        &lt;span class="keyword"&gt;get&lt;/span&gt; { &lt;span class="keyword"&gt;return&lt;/span&gt; suits[suitIndex]; }
    }

    &lt;span class="keyword"&gt;public override bool&lt;/span&gt; Equals(&lt;span class="keyword"&gt;object&lt;/span&gt; obj)
    {
        &lt;span class="type"&gt;Card&lt;/span&gt; card = obj &lt;span class="keyword"&gt;as &lt;/span&gt;&lt;span class="type"&gt;Card&lt;/span&gt;;
        &lt;span class="keyword"&gt;return&lt;/span&gt; (card != &lt;span class="keyword"&gt;null&lt;/span&gt;) &amp;amp;&amp;amp; &lt;span class="keyword"&gt;object&lt;/span&gt;.Equals(card.Value, &lt;span class="keyword"&gt;this&lt;/span&gt;.Value) &amp;amp;&amp;amp; &lt;span class="keyword"&gt;object&lt;/span&gt;.Equals(card.Suit, &lt;span class="keyword"&gt;this&lt;/span&gt;.Suit);
    }

    &lt;span class="keyword"&gt;public override int&lt;/span&gt; GetHashCode()
    {
        &lt;span class="keyword"&gt;int&lt;/span&gt; code = 13;
        code = (code * 23) + (&lt;span class="keyword"&gt;this&lt;/span&gt;.Value != &lt;span class="keyword"&gt;null&lt;/span&gt; ? &lt;span class="keyword"&gt;this&lt;/span&gt;.Value.GetHashCode() : 0);
        code = (code * 23) + (&lt;span class="keyword"&gt;this&lt;/span&gt;.Suit != &lt;span class="keyword"&gt;null&lt;/span&gt; ? &lt;span class="keyword"&gt;this&lt;/span&gt;.Suit.GetHashCode() : 0);

        &lt;span class="keyword"&gt;return&lt;/span&gt; code;
    }

    &lt;span class="keyword"&gt;public int&lt;/span&gt; CompareTo(&lt;span class="keyword"&gt;object&lt;/span&gt; obj)
    {
        &lt;span class="type"&gt;Card&lt;/span&gt; card = obj &lt;span class="keyword"&gt;as &lt;/span&gt;&lt;span class="type"&gt;Card&lt;/span&gt;;
        &lt;span class="keyword"&gt;if&lt;/span&gt; (obj == &lt;span class="keyword"&gt;null&lt;/span&gt;) &lt;span class="keyword"&gt;throw new &lt;/span&gt;&lt;span class="type"&gt;ArgumentNullException&lt;/span&gt;(&lt;span class="string"&gt;&amp;quot;obj&amp;quot;&lt;/span&gt;);
        &lt;span class="keyword"&gt;if&lt;/span&gt; (card == &lt;span class="keyword"&gt;null&lt;/span&gt;) &lt;span class="keyword"&gt;throw new &lt;/span&gt;&lt;span class="type"&gt;ArgumentException&lt;/span&gt;(&lt;span class="string"&gt;&amp;quot;The object has to be a card.&amp;quot;&lt;/span&gt;, &lt;span class="string"&gt;&amp;quot;obj&amp;quot;&lt;/span&gt;);

        &lt;span class="keyword"&gt;if&lt;/span&gt; (&lt;span class="keyword"&gt;this&lt;/span&gt;.valueIndex.Equals(card.valueIndex))
        {
            &lt;span class="keyword"&gt;return this&lt;/span&gt;.suitIndex.CompareTo(card.suitIndex);
        }
        &lt;span class="keyword"&gt;else&lt;/span&gt;
        {
            &lt;span class="keyword"&gt;return this&lt;/span&gt;.valueIndex.CompareTo(card.valueIndex);
        }
    }
}

&lt;span class="keyword"&gt;class &lt;/span&gt;&lt;span class="type"&gt;HighCardPlayer&lt;/span&gt;: &lt;span class="type"&gt;Player&lt;/span&gt;
{
    &lt;span class="keyword"&gt;private int&lt;/span&gt; score;

    &lt;span class="keyword"&gt;public int&lt;/span&gt; Score
    {
        &lt;span class="keyword"&gt;get&lt;/span&gt; { &lt;span class="keyword"&gt;return this&lt;/span&gt;.score; }
        &lt;span class="keyword"&gt;set&lt;/span&gt; { &lt;span class="keyword"&gt;this&lt;/span&gt;.score = &lt;span class="keyword"&gt;value&lt;/span&gt;; }
    }

    &lt;span class="keyword"&gt;public&lt;/span&gt; HighCardPlayer(&lt;span class="keyword"&gt;string&lt;/span&gt; name): &lt;span class="keyword"&gt;base&lt;/span&gt;(name)
    { }

}&lt;/pre&gt;
&lt;p&gt;A couple of things to notice:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;To really get the benefits of the Template Method Pattern, the method itself would have to be complex, relying on simple Primitive Operations implemented on derived classes. This example does a very &lt;span class="i"&gt;bad &lt;/span&gt;job illustrating this. A good example for this is the &lt;code&gt;Insert&lt;/code&gt; method of a data access object that would rely on derived classes operations like &lt;code&gt;GetTableName&lt;/code&gt; and &lt;code&gt;GetFieldMappings&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;This implementation is done to work with the first .NET Framework. This is on purpose. The reason for this lies right ahead.&lt;/li&gt;
&lt;li&gt;This game's implementation is not a very good one. It has a few flaws, but I didn't want the code to be more complex than it needed to. A &lt;code&gt;Deck&lt;/code&gt; class and refactoring &lt;code&gt;Card&lt;/code&gt; would be recommended, plus as it is, there is a better chance of having repeated value cards in the same hand than it should. This is beyond the scope of this post, so I'll leave it at that. (Originally planned on implementing Rock, Paper &amp; Scissors, but it seemed too cliché).&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;From here onwards, the focus will be on the &lt;code&gt;GetPlayers&lt;/code&gt; primitive operation.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;C# 1.0 - Where it all Started&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;GetPlayers&lt;/code&gt; method returns an &lt;code&gt;ArrayList&lt;/code&gt;. All we do with the returned list is enumerating through it so changing it to return an &lt;code&gt;IEnumerable&lt;/code&gt; makes perfect sense. This adds an extra drop of flexibility to game implementers. They can use an array, an &lt;code&gt;ArrayList&lt;/code&gt;, or even their own &lt;code&gt;IEnumerable&lt;/code&gt; implementation. To be fair, this isn't an extremely compelling reason, and I admit that on my C# 1.0 days, I would use &lt;code&gt;ArrayLists&lt;/code&gt; for pretty much everything. Not one of the smartest practices, I reckon, but did it anyways. Anyhow, this is the modified abstract method:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected abstract &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt; GetPlayers();&lt;/pre&gt;
&lt;p&gt;This adds no extra complexity to our previous implementation, although it does break it. We need to change our return type. New game implementations will thank us.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;C# 2.0 - If I Wanted to do all this Castings, I'd be in the Acting Industry&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;I will absolutely &lt;span class="b"&gt;not &lt;/span&gt;engage in a discussion about all the benefits of strong typed collections introduced at this point. I'll just say the world is now a better place thanks to generics and its very welcome nasty breaking changes. Unless there were an awful lot of game implementations out there, and little more to come, changing the method to return &lt;code&gt;IEnumerable&amp;lt;Player&amp;gt;&lt;/code&gt; is a must!&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected abstract &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt; GetPlayers();&lt;/pre&gt;
&lt;p&gt;Admittedly, this does add extra complexity to our HighCard class. I chose to make the players field a &lt;code&gt;List&amp;lt;HighCardPlayer&amp;gt;&lt;/code&gt;. This does avoid a whole lot of extra casts that had to be done before along the entire class, but the &lt;code&gt;GetPlayers&lt;/code&gt; method did become longer:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected override &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt; GetPlayers()
{
    &lt;span class="keyword"&gt;return&lt;/span&gt; players.ConvertAll&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt;(&lt;span class="keyword"&gt;delegate&lt;/span&gt;(&lt;span class="type"&gt;HighCardPlayer&lt;/span&gt; player)
    {
        &lt;span class="keyword"&gt;return&lt;/span&gt; player;
    });
}&lt;/pre&gt;
&lt;p&gt;Still, let analyze what the advantages are:&lt;/p&gt;
&lt;p&gt;For one, if our players list was of the &lt;code&gt;Player&lt;/code&gt; type, no extra code would've been required. Also, as for now, on our implementations we can take advantage on the newly incorporated &lt;code&gt;yield&lt;/code&gt; keyword. If you don't like anonymous methods, the &lt;code&gt;GetPlayers&lt;/code&gt; method can also be written this way:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected override &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt; GetPlayers()
{
    &lt;span class="keyword"&gt;foreach&lt;/span&gt; (&lt;span class="type"&gt;Player&lt;/span&gt; player &lt;span class="keyword"&gt;in&lt;/span&gt; players)
    {
        &lt;span class="keyword"&gt;yield return&lt;/span&gt; player;
    }
}&lt;/pre&gt;
&lt;p&gt;Yes, it is &lt;span class="b"&gt;that &lt;/span&gt;simple. But it gets even better; consider that the game you are implementing has a constant amount of players. You could be creating a backgammon game with &lt;code&gt;player1&lt;/code&gt; and &lt;code&gt;player2&lt;/code&gt;. This would look just like this:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected override &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt; GetPlayers()
{
    &lt;span class="keyword"&gt;yield return&lt;/span&gt; player1;
    &lt;span class="keyword"&gt;yield return&lt;/span&gt; player2;
}&lt;/pre&gt;
&lt;p&gt;Although this is two lines of code, it is way more readable than what we would've done before:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected override &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt; GetPlayers()
{
    &lt;span class="keyword"&gt;return new &lt;/span&gt;&lt;span class="type"&gt;Player&lt;/span&gt;[] { player1, player2 };
}&lt;/pre&gt;
&lt;p&gt;Even for a solitaire game, return a 1 item enumeration is simpler, and in the probably not applicable case of a no playered game:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected override &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt; GetPlayers()
{
    &lt;span class="keyword"&gt;yield break&lt;/span&gt;;
}&lt;/pre&gt;
&lt;p&gt;So the yield keyword will offer our implementers a whole new universe of possibilities.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;C# 3.0 – Linqing the OOP World with the Functional World&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;As you've already guessed, now C# 3.0 came along, and even more flexibility is added to our &lt;code&gt;GetPlayers&lt;/code&gt; method. Thanks to the functional programming fellows, extension methods, lambda expressions and linq is introduced. Now more complex games, with say eliminations between rounds are pretty simple to implement.&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected override &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt; GetPlayers()
{
    &lt;span class="keyword"&gt;return&lt;/span&gt; players
        .Where(player =&amp;gt; !player.IsEliminated)
        .OrderByDescending(player =&amp;gt; player.Score)
        .Cast&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt;();
}&lt;/pre&gt;
&lt;p&gt;Or even in query language:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected override &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt; GetPlayers()
{
    &lt;span class="keyword"&gt;return from&lt;/span&gt; highCardplayer &lt;span class="keyword"&gt;in&lt;/span&gt; players
           &lt;span class="keyword"&gt;let&lt;/span&gt; player = (&lt;span class="type"&gt;Player&lt;/span&gt;)highCardplayer
           &lt;span class="keyword"&gt;where&lt;/span&gt; !highCardplayer.IsEliminated
           &lt;span class="keyword"&gt;orderby&lt;/span&gt; highCardplayer.Score &lt;span class="keyword"&gt;descending&lt;/span&gt;
           &lt;span class="keyword"&gt;select&lt;/span&gt; player;
}&lt;/pre&gt;
&lt;p&gt;Even our version in &lt;code&gt;HighCard&lt;/code&gt; gets slightly simplified due to extension methods:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected override &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt; GetPlayers()
{
    &lt;span class="keyword"&gt;return&lt;/span&gt; players.Cast&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt;();
}&lt;/pre&gt;
&lt;p&gt;The beauty in this is that we have introduced no breaking changes what so ever, in fact, our &lt;code&gt;GameBase&lt;/code&gt; class hasn't even changed.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;C# 4.0 – A Peek into the Future&lt;/span&gt;&lt;/class&gt;
&lt;p&gt;With C# 4.0 we will be able to take advantage of the covariant aspect of &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt;. Basically, an &lt;code&gt;IEnumerable&amp;lt;HighCardPlayer&amp;gt;&lt;/code&gt; can be implicitly converted to &lt;code&gt;IEnumerable&amp;lt;Player&amp;gt;&lt;/code&gt;. This takes us back to our method being as simple as it started out being:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;protected override &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt; GetPlayers()
{
    &lt;span class="keyword"&gt;return&lt;/span&gt; players;
}&lt;/pre&gt;
&lt;p&gt;Notice how players is &lt;code&gt;List&amp;lt;HighCardPlayer&amp;gt;&lt;/code&gt; which in turn is an &lt;code&gt;IEnumerable&amp;lt;HighCardPlayer&amp;gt;&lt;/code&gt;, and thanks to covariance, it is also an &lt;code&gt;IEnumerable&amp;lt;Player&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Our &lt;code&gt;GameBase&lt;/code&gt;class didn't change and no breaking changes were introduced. Still, interesting enough, there is a chance that switching to C# 4.0 will introduce a breaking change. If we had something like this:&lt;/p&gt;
&lt;pre&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt; playerEnum = players;

&lt;span class="keyword"&gt;if&lt;/span&gt; (playerEnum &lt;span class="keyword"&gt;is &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Player&lt;/span&gt;&amp;gt;)
{
    &lt;span class="comment"&gt;// Do something&lt;/span&gt;
}
&lt;span class="keyword"&gt;else if&lt;/span&gt; (playerEnum &lt;span class="keyword"&gt;is &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;HighCardPlayer&lt;/span&gt;&amp;gt;)
{
    &lt;span class="comment"&gt;// Do something else&lt;/span&gt;
}&lt;/pre&gt;
&lt;p&gt;Now, the second block will be unreachable since every &lt;code&gt;IEnumerable&amp;lt;HighCardPlayer&amp;gt;&lt;/code&gt; is in fact also an &lt;code&gt;IEnumerable&amp;lt;Player&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;The Reason behind this Post&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;I've been working on a code generation project. For example, the class generator makes full use of Template Methods that use operations like &lt;code&gt;GetFields&lt;/code&gt;, &lt;code&gt;GetMethods&lt;/code&gt;, &lt;code&gt;GetProperties&lt;/code&gt; and even &lt;code&gt;GetDecorators&lt;/code&gt;. These operations have changed during time taking advantage of everything noted above, and I found it very interesting. I thought I'd share.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;Random thoughts: &lt;/span&gt;The template method pattern isn't really the reason of all the things that were shown here, the responsible is the &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; interface. I might as well have used an interface with &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; methods or properties, but took this opportunity to talk a little about this pattern. I usually find it extremely useful, and the simplicity of it makes it yet more desirable. Pretty much like everything else, the value is benefit/complexity. Having such low complexity makes it very valuable, and I love the &lt;a href="http://en.wikipedia.org/wiki/KISS_principle"&gt;KISS principle&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;On a personal note, I wish my very good friend Gonzalo a very happy birthday. I hope you enjoy this post and good luck on your future endeavors!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1562048197280495196-2101557006924145014?l=fernandonicolet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fernandonicolet.blogspot.com/feeds/2101557006924145014/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fernandonicolet.blogspot.com/2009/06/template-method-pattern-ienumerable.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/2101557006924145014'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/2101557006924145014'/><link rel='alternate' type='text/html' href='http://fernandonicolet.blogspot.com/2009/06/template-method-pattern-ienumerable.html' title='Template Method Pattern &amp; IEnumerable&lt;T&gt;'/><author><name>Fernando Nicolet</name><uri>http://www.blogger.com/profile/04402615396818391251</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='27' height='32' src='http://3.bp.blogspot.com/_mmG4Sk1Z5oY/SgTqce9blEI/AAAAAAAAAAY/IazFgTXhp0U/S220/profile.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1562048197280495196.post-1641564101082871704</id><published>2009-06-11T19:18:00.002-03:00</published><updated>2009-07-12T17:38:03.396-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='MSDN Forums'/><category scheme='http://www.blogger.com/atom/ns#' term='Forums Browser'/><category scheme='http://www.blogger.com/atom/ns#' term='Personal'/><title type='text'>MSDN Forums Browser</title><content type='html'>&lt;p&gt;Yesterday was an exciting day; &lt;a href="http://forumsbrowser.codeplex.com/"&gt;David Morton's MSDN Forums Browser&lt;/a&gt; was released at &lt;a href="http://www.codeplex.com"&gt;Codeplex&lt;/a&gt;. It's on a very alpha state, but it seems clear to me that has the potential to become an excellent and very valuable tool.&lt;/p&gt;
&lt;p&gt;Yet today it got even better, he made me a part of his team! It's a wonderful opportunity to work side by side with some extremely talented developers. I'm thrilled about it, and I will embrace this opportunity to learn as much as I can, while hopefully becoming a valuable asset for the team.&lt;/p&gt;
&lt;p&gt;Needless to say I encourage you to download it, try it out and give as much feedback as you can.&lt;/p&gt;
&lt;img src="http://ygjpyg.blu.livefilestore.com/y1pPzolNuTbtBjoAaKvse1TjTCdmwIgwA8RG_iAD1H0tYVINaWzUsREZM4wg8TD-60vVf14UJK9nTB2Vmny05L9tSiS7O-KoKuP/forumsbrowser.jpg" alt="MSDN Forums Browser's Screenshot" title="MSDN Forums Browser's Screenshot"/&gt;
&lt;p&gt;Link to project: &lt;a href="http://forumsbrowser.codeplex.com/"&gt;http://forumsbrowser.codeplex.com/&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/1562048197280495196-1641564101082871704?l=fernandonicolet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fernandonicolet.blogspot.com/feeds/1641564101082871704/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fernandonicolet.blogspot.com/2009/06/msdn-forums-browser.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/1641564101082871704'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/1641564101082871704'/><link rel='alternate' type='text/html' href='http://fernandonicolet.blogspot.com/2009/06/msdn-forums-browser.html' title='MSDN Forums Browser'/><author><name>Fernando Nicolet</name><uri>http://www.blogger.com/profile/04402615396818391251</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='27' height='32' src='http://3.bp.blogspot.com/_mmG4Sk1Z5oY/SgTqce9blEI/AAAAAAAAAAY/IazFgTXhp0U/S220/profile.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1562048197280495196.post-7347058244727417457</id><published>2009-05-30T16:39:00.008-03:00</published><updated>2009-07-12T17:38:02.951-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Fun'/><category scheme='http://www.blogger.com/atom/ns#' term='CIL'/><category scheme='http://www.blogger.com/atom/ns#' term='Performance'/><title type='text'>Who's on First</title><content type='html'>&lt;p&gt;This is a follow-up to my previous post: &lt;a href="http://blog.fernandonicolet.com/2009/05/swap-ints-two-variables-no-waiting.html"&gt;Swap Ints, Two Variables, No Waiting&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;While analyzing my method's CIL, I thought that maybe I could implement a faster swap. Maybe there is a way to implement a method that doesn't need a temp variable but without all the overhead we've seen with xor. Well, the following came up:&lt;/p&gt;
&lt;pre class="cil"&gt;.method public hidebysig static void  SwapIntsCil(int32&amp; first,
                                                  int32&amp; second) cil managed
{
  // Code size       9 (0x9)
  .maxstack  4
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  ldind.i4
  IL_0003:  ldarg.1
  IL_0004:  ldarg.0
  IL_0005:  ldind.i4
  IL_0006:  stind.i4
  IL_0007:  stind.i4
  IL_0008:  ret
} // end of method IntSwapper::SwapIntsCil&lt;/pre&gt;
&lt;p&gt;Let's see what it does:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;span class="b"&gt;IL_0000 &lt;/span&gt;Pushes first's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0001 &lt;/span&gt;Pushes second's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0002 &lt;/span&gt;Pops the address to fetch and push the actual Int32 value.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0003 &lt;/span&gt;Pushes second's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0004 &lt;/span&gt;Pushes first's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0005 &lt;/span&gt;Pops the address to fetch and push the actual Int32 value.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0006 &lt;/span&gt;Pops first's value and second's address to store the value at the address.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0007 &lt;/span&gt;Pops second's value and first's address to store the value at the address.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0008 &lt;/span&gt;Gets the hell outta here.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;a href="#" onclick="javascript:ShowHide('swapIntCilImage'); return false;"&gt;Click to display diagram.&lt;/a&gt;
&lt;div id="swapIntCilImage" class="hidden"&gt;&lt;img src="http://ygjpyg.blu.livefilestore.com/y1p1exC6ZNeQrtCsvA9pByIcWcsnxn4L0sRo7oWkZwHYbeuoYu-AV6iOtib9MfAOj0NJhNUaNDZkUcM_q5k-eR8NSCJNV0ROKZI/swapintscil.png" /&gt;&lt;/div&gt;&lt;/p&gt;
&lt;p&gt;To sum up, this method would use 4 levels of stack, declare no local variables, load 4 addresses, load 2 values through these addresses, store 2 values to these addresses and perform no operations.&lt;/p&gt;
&lt;p&gt;In order to implement this, I moved previous swaps into a separate Assembly called KeepItSharp (yes, I'm &lt;span class="i"&gt;that &lt;/span&gt;original) and to a class called IntSwapper. Built it in release mode, opened it with ildasm and dumped the CIL code. Added my new method and compiled it with ilasm. Time to test it!&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;static void&lt;/span&gt; Main(&lt;span class="keyword"&gt;string&lt;/span&gt;[] args)
{
    &lt;span class="keyword"&gt;int&lt;/span&gt; a = 15;
    &lt;span class="keyword"&gt;int&lt;/span&gt; b = 320;
    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;a: {0}\tb: {1}&amp;quot;&lt;/span&gt;, a, b);

    KeepItSharp.&lt;span class="type"&gt;IntSwapper&lt;/span&gt;.SwapIntsCil(&lt;span class="keyword"&gt;ref&lt;/span&gt; a, &lt;span class="keyword"&gt;ref&lt;/span&gt; b);

    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;a: {0}\tb: {1}&amp;quot;&lt;/span&gt;, a, b);
}&lt;/pre&gt;
&lt;p&gt;And the result is... &amp;lt;drumroll&amp;gt;&lt;/p&gt;
&lt;pre class="console"&gt;a: 15   b: 320
a: 320  b: 15
Press any key to continue . . .&lt;/pre&gt;
&lt;p&gt;Cool… my first CIL code and it works! Well, can't wait to see if it actually is faster than the conventional swap. Here it goes:&lt;/p&gt;
&lt;p&gt;Benchmarking code is omitted because it's analogue to the one on my previous post.&lt;/p&gt;
&lt;pre class="console"&gt;SwapIntsXor: 00.559 - SwapIntsCil: 00.190 - SwapInts: 00.200
SwapIntsXor: 00.543 - SwapIntsCil: 00.189 - SwapInts: 00.194
SwapIntsXor: 00.544 - SwapIntsCil: 00.191 - SwapInts: 00.194
SwapIntsXor: 00.545 - SwapIntsCil: 00.190 - SwapInts: 00.190
SwapIntsXor: 00.549 - SwapIntsCil: 00.193 - SwapInts: 00.192
Press any key to continue . . .&lt;/pre&gt;
&lt;p&gt;Darn it! It seems to be a close one. OK, let's call it a tie.&lt;/p&gt;
&lt;p&gt;Now, it seemed like fun to see what &lt;a href="http://www.red-gate.com/products/reflector/" target="_blank"&gt;Red Gate's .NET Reflector &lt;/a&gt;had to say about this method, and the result is pretty peculiar. Check it out:&lt;/p&gt;
&lt;pre style="background-color: #FFFFE1; font-family: Tahoma; font-size: small"&gt;&lt;span style="color: #1000A0"&gt;public static &lt;/span&gt;&lt;span style="color: #006018"&gt;void &lt;/span&gt;&lt;span style="color: #000000; font-weight: bold"&gt;SwapIntsCil&lt;/span&gt;&lt;span style="color: #000000"&gt;(&lt;/span&gt;&lt;span style="color: #1000A0"&gt;ref &lt;/span&gt;&lt;span style="color: #006018"&gt;int &lt;/span&gt;&lt;span style="color: #000000"&gt;first, &lt;/span&gt;&lt;span style="color: #1000A0"&gt;ref &lt;/span&gt;&lt;span style="color: #006018"&gt;int &lt;/span&gt;&lt;span style="color: #000000"&gt;second)&lt;/span&gt;
&lt;span style="color: #000000"&gt;{&lt;/span&gt;
&lt;span style="color: #006018"&gt;    second&lt;/span&gt;&lt;span style="color: #000000"&gt; = &lt;/span&gt;&lt;span style="color: #006018"&gt;first&lt;/span&gt;&lt;span style="color: #000000"&gt;;&lt;/span&gt;
&lt;span style="color: #006018"&gt;    first&lt;/span&gt;&lt;span style="color: #000000"&gt; = &lt;/span&gt;&lt;span style="color: #006018"&gt;second&lt;/span&gt;&lt;span style="color: #000000"&gt;;&lt;/span&gt;
&lt;span style="color: #000000"&gt;}&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;And &lt;span class="i"&gt;this &lt;/span&gt;works? Actually I wish that reflector would have thrown an error instead of showing this mysterious piece of coding that should've never worked.&lt;/p&gt;
&lt;p&gt;The whole time while writing these last two posts, I kept thinking about Abbott and Costello's &lt;span class="i"&gt;&amp;quot;Who's on First&amp;quot;&lt;/span&gt;. Who's on first, what's on second, and on third? I don't know, I'm not using a temp variable!&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;Random thoughts: &lt;/span&gt;Aside from being cool to code some CIL, what left me thinking most was Reflector's behavior. For one, I will &lt;span class="b"&gt;not &lt;/span&gt;stop using Reflector since the benefits are huge and these scenarios very scarce. On another note, this means that using CIL code directly allows us to write code that can't be translated to C# with reflecting tools. This seems pretty useful for licensing code, for example, although it would be easier to just code it in C and p/invoke it.&lt;/p&gt;
&lt;p&gt;You can download KeepItSharp.dll &lt;a href="http://ygjpyg.blu.livefilestore.com/y1pK9qPp-XSLXnN-WmexFJ_rHK_n-52lE--Gen_7FO0Djm4NEgZatSE_SY9tH-EArT71-YzsCi6nCkafDIuKmuJ0-SXOuZU4us5/KeepItSharp.dll"&gt;here&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/1562048197280495196-7347058244727417457?l=fernandonicolet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fernandonicolet.blogspot.com/feeds/7347058244727417457/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fernandonicolet.blogspot.com/2009/05/whos-on-first.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/7347058244727417457'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/7347058244727417457'/><link rel='alternate' type='text/html' href='http://fernandonicolet.blogspot.com/2009/05/whos-on-first.html' title='Who&apos;s on First'/><author><name>Fernando Nicolet</name><uri>http://www.blogger.com/profile/04402615396818391251</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='27' height='32' src='http://3.bp.blogspot.com/_mmG4Sk1Z5oY/SgTqce9blEI/AAAAAAAAAAY/IazFgTXhp0U/S220/profile.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1562048197280495196.post-6488195085411950264</id><published>2009-05-28T19:36:00.009-03:00</published><updated>2009-07-12T17:38:06.247-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Fun'/><category scheme='http://www.blogger.com/atom/ns#' term='CIL'/><category scheme='http://www.blogger.com/atom/ns#' term='Performance'/><title type='text'>Swap Ints, Two Variables, No Waiting</title><content type='html'>&lt;p&gt;Who hasn't had to swap two ints? Everyone who implemented a sort algorithm, for example, had to swap two values. What does this function look like? Probably something like this:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;static void&lt;/span&gt; SwapInts(&lt;span class="keyword"&gt;ref int&lt;/span&gt; first, &lt;span class="keyword"&gt;ref int&lt;/span&gt; second)
{
    &lt;span class="keyword"&gt;int&lt;/span&gt; aux = first;
    first = second;
    second = aux;
}&lt;/pre&gt;
&lt;p&gt;And it works too!&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;static void&lt;/span&gt; Main(&lt;span class="keyword"&gt;string&lt;/span&gt;[] args)
{
    &lt;span class="keyword"&gt;int&lt;/span&gt; a = 15;
    &lt;span class="keyword"&gt;int&lt;/span&gt; b = 320;
    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;a: {0}\tb: {1}&amp;quot;&lt;/span&gt;, a, b);

    SwapInts(&lt;span class="keyword"&gt;ref&lt;/span&gt; a, &lt;span class="keyword"&gt;ref&lt;/span&gt; b);

    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;a: {0}\tb: {1}&amp;quot;&lt;/span&gt;, a, b);
}&lt;/pre&gt;
&lt;pre class="console"&gt;a: 15   b: 320
a: 320  b: 15
Press any key to continue . . .&lt;/pre&gt;
&lt;p&gt;My parents are so proud!&lt;/p&gt;
&lt;p&gt;Anyways, a co-worker challenged me to implement the &lt;code&gt;SwapInts&lt;/code&gt; method without using an auxiliary variable. We all know that patience is a virtue, and I know that it is something I should work on. I got frustrated within minutes and demanded the solution to this. It turned out not so complex after all. Check it out:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;static void&lt;/span&gt; SwapIntsXor(&lt;span class="keyword"&gt;ref int&lt;/span&gt; first, &lt;span class="keyword"&gt;ref int&lt;/span&gt; second)
{
    first ^= second;
    second ^= first;
    first ^= second;
}&lt;/pre&gt;
&lt;p&gt;This works because xoring first and second produces a number that when xored with first we get second and when xored with second we get first. Pretty slick! Let's take a deeper look. Remember the xor table?&lt;/p&gt;
&lt;p&gt;&lt;table&gt;&lt;tr&gt;&lt;th&gt;XOR&lt;/th&gt;&lt;th&gt;0&lt;/th&gt;&lt;th&gt;1&lt;/th&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/p&gt;
&lt;p&gt;Now, a pretty cool characteristic about xor is that when you xor twice you get back where you started:&lt;/p&gt;
&lt;p&gt;0011&lt;br /&gt;
&lt;span class="u"&gt;0101&lt;/span&gt;&lt;br /&gt;
0110&lt;/p&gt;
&lt;p&gt;And once again…&lt;/p&gt;
&lt;p&gt;0110&lt;br /&gt;
&lt;span class="u"&gt;0101&lt;/span&gt;&lt;br /&gt;
0011&lt;/p&gt;
&lt;p&gt;Bingo!&lt;/p&gt;
&lt;p&gt;Now lets breakdown our new method. Consider A to be the first value, B the second and C the xored value.&lt;/p&gt;
&lt;p&gt;first ^= second; -&gt; first is C / second is B&lt;br /&gt;
second ^= first; -&gt; first is C / second is A&lt;br /&gt;
first ^= second; -&gt; first is B / second is A&lt;/p&gt;
&lt;p&gt;This got me thinking a little. Of course this has absolutely no use in real life code, but it seemed as in terms of performance we could have a little improvement. So, no time to waste, I benchmarked them:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;static void&lt;/span&gt; Main(&lt;span class="keyword"&gt;string&lt;/span&gt;[] args)
{
    &lt;span class="keyword"&gt;int&lt;/span&gt; a = 15;
    &lt;span class="keyword"&gt;int&lt;/span&gt; b = 320;

    &lt;span class="comment"&gt;// Warm up&lt;/span&gt;
    SwapIntsXor (&lt;span class="keyword"&gt;ref&lt;/span&gt; a,&lt;span class="keyword"&gt;ref&lt;/span&gt; b);
    SwapInts (&lt;span class="keyword"&gt;ref&lt;/span&gt; a, &lt;span class="keyword"&gt;ref&lt;/span&gt; b);

    Benchmark(100000000, 5);
}

&lt;span class="keyword"&gt;static void&lt;/span&gt; Benchmark(&lt;span class="keyword"&gt;int&lt;/span&gt; innerIterations, &lt;span class="keyword"&gt;int&lt;/span&gt; outterIterations)
{
    &lt;span class="keyword"&gt;int&lt;/span&gt; a = 15;
    &lt;span class="keyword"&gt;int&lt;/span&gt; b = 320;
    &lt;span class="type"&gt;Stopwatch&lt;/span&gt; sw = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;Stopwatch&lt;/span&gt;();

    &lt;span class="keyword"&gt;for&lt;/span&gt; (&lt;span class="keyword"&gt;int&lt;/span&gt; i = 0; i &amp;lt; outterIterations; i++)
    {
        sw.Start();
        &lt;span class="keyword"&gt;for&lt;/span&gt; (&lt;span class="keyword"&gt;int&lt;/span&gt; j = 0; j &amp;lt; innerIterations; j++)
        {
            SwapInts(&lt;span class="keyword"&gt;ref&lt;/span&gt; a, &lt;span class="keyword"&gt;ref&lt;/span&gt; b);
        }
        sw.Stop();
        &lt;span class="type"&gt;Console&lt;/span&gt;.Write(&lt;span class="string"&gt;&amp;quot;SwapInts: {0:ss.fff} - &amp;quot;&lt;/span&gt;, &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;DateTime&lt;/span&gt;(sw.Elapsed.Ticks));
        sw.Reset();

        sw.Start();
        &lt;span class="keyword"&gt;for&lt;/span&gt; (&lt;span class="keyword"&gt;int&lt;/span&gt; j = 0; j &amp;lt; innerIterations; j++)
        {
            SwapIntsXor(&lt;span class="keyword"&gt;ref&lt;/span&gt; a, &lt;span class="keyword"&gt;ref&lt;/span&gt; b);
        }
        sw.Stop();
        &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;SwapIntsXor: {0:ss.fff}&amp;quot;&lt;/span&gt;, &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;DateTime&lt;/span&gt;(sw.Elapsed.Ticks));
        sw.Reset();
    }
}&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre class="console"&gt;SwapInts: 00.190 - SwapXor: 00.558
SwapInts: 00.185 - SwapXor: 00.548
SwapInts: 00.189 - SwapXor: 00.547
SwapInts: 00.187 - SwapXor: 00.554
SwapInts: 00.187 - SwapXor: 00.546
Press any key to continue . . .&lt;/pre&gt;
&lt;p&gt;The conventional swap is faster than the new one. I can't stress enough that this was just for experimental purposes and to satisfy my own curiosity. By any means, even if with xor was significantly faster, would I recommend it since the conventional one is well known, straight forward and much, much easier to understand.&lt;/p&gt;
&lt;p&gt;Anyways, since I've never really tried to understand any CIL, this seemed like a sweet opportunity to take the first steps and understand what makes it slower. Let's analyze the &lt;code&gt;SwapInts&lt;/code&gt; method:&lt;/p&gt;
&lt;pre class="cil"&gt;.method private hidebysig static void  SwapInts(int32&amp; first,
                                                int32&amp; second) cil managed
{
  // Code size       11 (0xb)
  .maxstack  2
  .locals init ([0] int32 aux)
  IL_0000:  ldarg.0
  IL_0001:  ldind.i4
  IL_0002:  stloc.0
  IL_0003:  ldarg.0
  IL_0004:  ldarg.1
  IL_0005:  ldind.i4
  IL_0006:  stind.i4
  IL_0007:  ldarg.1
  IL_0008:  ldloc.0
  IL_0009:  stind.i4
  IL_000a:  ret
} // end of method Program::SwapInts&lt;/pre&gt;
&lt;ul&gt;&lt;li&gt;&lt;span class="b"&gt;IL_0000 &lt;/span&gt;Pushes first's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0001 &lt;/span&gt;Pops the address to fetch and push the actual Int32 value.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0002 &lt;/span&gt;Pops first's value and stores it into local variable aux.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0003 &lt;/span&gt;Pushes first's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0004 &lt;/span&gt;Pushes second's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0005 &lt;/span&gt;Pops the address to fetch and push the actual Int32 value.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0006 &lt;/span&gt;Pops second's value and first's address to store the value at the address.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0007 &lt;/span&gt;Pushes second's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0008 &lt;/span&gt;Pushes the value at local variable aux.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0009 &lt;/span&gt;Pops aux's value and second's address to store the value at the address.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_000a &lt;/span&gt;Gets the hell outta here.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;a href="#" onclick="javascript:ShowHide('swapIntImage'); return false;"&gt;Click to display diagram.&lt;/a&gt;
&lt;div id="swapIntImage" class="hidden"&gt;&lt;img src="http://ygjpyg.blu.livefilestore.com/y1pvZJCkAJBZ1BDOn6Kdt2rkuJKYzLjozFhN8G6Bok4ENKG4EVLVBS5c0EsIJ_MLe0-t831zI5Ci-R1yLudRtGl5lXWhOcmP4aW/swapints.png" /&gt;&lt;/div&gt;&lt;/p&gt;
&lt;p&gt;To sum up, this method uses only 2 levels of the stack, declares 1 local variable, loads 4 addresses, loads 2 values through these addresses, loads 1 value through a local variable, stores 2 values to addresses, stores 1 value to a local variable and performs no operations.&lt;/p&gt;
&lt;p&gt;&lt;span class="u"&gt;Note:&lt;/span&gt; The stack mentioned above is a conceptual stack called the Virtual Execution System. This is not &lt;span class="b"&gt;"the stack"&lt;/span&gt; everyone talks about when referring to where the local and parameter value types are stored. That being said lets move on...&lt;/p&gt;
&lt;p&gt;Now we should check out the &lt;code&gt;SwapIntsXor&lt;/code&gt; method:&lt;/p&gt;
&lt;pre class="cil"&gt;.method private hidebysig static void  SwapIntsXor(int32&amp; first,
                                                   int32&amp; second) cil managed
{
  // Code size       22 (0x16)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  dup
  IL_0002:  ldind.i4
  IL_0003:  ldarg.1
  IL_0004:  ldind.i4
  IL_0005:  xor
  IL_0006:  stind.i4
  IL_0007:  ldarg.1
  IL_0008:  dup
  IL_0009:  ldind.i4
  IL_000a:  ldarg.0
  IL_000b:  ldind.i4
  IL_000c:  xor
  IL_000d:  stind.i4
  IL_000e:  ldarg.0
  IL_000f:  dup
  IL_0010:  ldind.i4
  IL_0011:  ldarg.1
  IL_0012:  ldind.i4
  IL_0013:  xor
  IL_0014:  stind.i4
  IL_0015:  ret
} // end of method Program::SwapIntsXor&lt;/pre&gt;
&lt;p&gt;It's seems heavier already! Let's start:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;span class="b"&gt;IL_0000 &lt;/span&gt;Pushes first's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0001 &lt;/span&gt;Duplicates the top value of the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0002 &lt;/span&gt;Pops the address to fetch and push the actual Int32 value.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0003 &lt;/span&gt;Pushes second's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0004 &lt;/span&gt;Pops the address to fetch and push the actual Int32 value.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0005 &lt;/span&gt;Pops second's value and first's value to perform a xor and push the result.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0006 &lt;/span&gt;Pops the xor's result and first's address to store the value at the address.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0007 &lt;/span&gt;Pushes second's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0008 &lt;/span&gt;Duplicates the top value of the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0009 &lt;/span&gt;Pops the address to fetch and push the actual Int32 value.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_000a &lt;/span&gt;Pushes first's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_000b &lt;/span&gt;Pops the address to fetch and push the actual Int32 value.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_000c &lt;/span&gt;Pops first's value and second's value to perform a xor and push the result.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_000d &lt;/span&gt;Pops the xor's result and second's address to store the value at the address.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_000e &lt;/span&gt;Pushes first's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_000f &lt;/span&gt;Duplicates the top value of the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0010 &lt;/span&gt;Pops the address to fetch and push the actual Int32 value.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0011 &lt;/span&gt;Pushes second's address into the stack.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0012 &lt;/span&gt;Pops the address to fetch and push the actual Int32 value.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0013 &lt;/span&gt;Pops second's value and first's value to perform a xor and push the result.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0014 &lt;/span&gt;Pops the xor's result and first's address to store the value at the address.&lt;/li&gt;
&lt;li&gt;&lt;span class="b"&gt;IL_0015 &lt;/span&gt;Gets the hell outta here.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;a href="#" onclick="javascript:ShowHide('swapIntXorImage'); return false;"&gt;Click to display diagram.&lt;/a&gt;
&lt;div id="swapIntXorImage" class="hidden"&gt;&lt;img src="http://ygjpyg.blu.livefilestore.com/y1pDWQTDK879Pbw7EhObnJs5TYtpecCBprJq-_NjOL9s-oOcLqX5_H9aQfpxPvtHP5U9tt2kHSuJ2w5ki0q43HbYuA7F_g3P_x0/swapintsxor.png" /&gt;&lt;/div&gt;&lt;/p&gt;
&lt;p&gt;To sum up, this method uses 3 levels of stack, declares no local variables, loads 6 addresses, duplicates 3 of these, loads 6 values through these addresses, stores 3 values to addresses and performs 3 operations. This one is definitely heavier than the previous.&lt;/p&gt;
&lt;p&gt;I believe is worth noting that CIL doesn't necessarily translate directly or proportionally to machine code, it's just one step closer. Analyzing the machine code is a whole other story; a story I don't plan getting close to anywhere in the near future.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;Random thoughts: &lt;/span&gt;I wonder why &lt;code&gt;.maxstack&lt;/code&gt; is set on 8 for &lt;code&gt;SwapIntXor &lt;/code&gt;when 3 would suffice, but for what I've seen this is pretty common. Anyhow, I have no idea if anyone will find all this information useful at all, but it was an extremely helpful exercise for me and a lot of fun.&lt;/p&gt;
&lt;p&gt;&lt;span class="u"&gt;Edit:&lt;/span&gt; Switched the benchmark. It was previously done in debug mode.&lt;/p&gt;
&lt;p&gt;Follow up: &lt;a href="http://blog.fernandonicolet.com/2009/05/whos-on-first.html"&gt;Who's of First&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/1562048197280495196-6488195085411950264?l=fernandonicolet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fernandonicolet.blogspot.com/feeds/6488195085411950264/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fernandonicolet.blogspot.com/2009/05/swap-ints-two-variables-no-waiting.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/6488195085411950264'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/6488195085411950264'/><link rel='alternate' type='text/html' href='http://fernandonicolet.blogspot.com/2009/05/swap-ints-two-variables-no-waiting.html' title='Swap Ints, Two Variables, No Waiting'/><author><name>Fernando Nicolet</name><uri>http://www.blogger.com/profile/04402615396818391251</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='27' height='32' src='http://3.bp.blogspot.com/_mmG4Sk1Z5oY/SgTqce9blEI/AAAAAAAAAAY/IazFgTXhp0U/S220/profile.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1562048197280495196.post-1638429816909385968</id><published>2009-05-24T14:27:00.003-03:00</published><updated>2009-07-12T17:37:58.306-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Value Types'/><category scheme='http://www.blogger.com/atom/ns#' term='Reflection'/><title type='text'>Evil Mutant Value Types</title><content type='html'>&lt;h5&gt;Setting a stucture's property through Reflection&lt;/h5&gt;
&lt;p&gt;Not so long ago I was presented with the following problem. Consider the following struct:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public struct &lt;/span&gt;&lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt;
{

    &lt;span class="keyword"&gt;private int&lt;/span&gt; x;

    &lt;span class="keyword"&gt;public&lt;/span&gt; UglyMutableStruct(&lt;span class="keyword"&gt;int&lt;/span&gt; x)
    {
        &lt;span class="keyword"&gt;this&lt;/span&gt;.x = x;
    }

    &lt;span class="keyword"&gt;public int&lt;/span&gt; X
    {
        &lt;span class="keyword"&gt;get&lt;/span&gt; { &lt;span class="keyword"&gt;return this&lt;/span&gt;.x; }
        &lt;span class="keyword"&gt;set&lt;/span&gt; { &lt;span class="keyword"&gt;this&lt;/span&gt;.x = &lt;span class="keyword"&gt;value&lt;/span&gt;; }
    }

    &lt;span class="keyword"&gt;public override string&lt;/span&gt; ToString()
    {
        &lt;span class="keyword"&gt;return string&lt;/span&gt;.Format(&lt;span class="string"&gt;&amp;quot;X: {0}&amp;quot;&lt;/span&gt;, X);
    }

}&lt;/pre&gt;
&lt;p&gt;And the simple task was to set X's value through reflection:&lt;/p&gt;
&lt;pre&gt;&lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt; instance = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt;(10);
&lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(instance);

&lt;span class="type"&gt;Type&lt;/span&gt; myType = &lt;span class="keyword"&gt;typeof&lt;/span&gt;(&lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt;);

&lt;span class="type"&gt;PropertyInfo&lt;/span&gt; propertyX = myType.GetProperty(&lt;span class="string"&gt;&amp;quot;X&amp;quot;&lt;/span&gt;);
propertyX.SetValue(instance, 15, &lt;span class="keyword"&gt;null&lt;/span&gt;);

&lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(instance);&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre class="console"&gt;X: 10
X: 10
Press any key to continue . . .&lt;/pre&gt;
&lt;p&gt;Puzzled by this seemingly bizarre behavior, I searched the web to find a solution. I found a couple of people saying that it just can't be done, live with it. What I didn't find and wanted to know is &lt;span class="b"&gt;why&lt;/span&gt; it can't be done. So, since I saw little analysis to be done to this particular bit of code I checked out the CIL through ildasm to see what could be happening. I came to my attention that instance was being boxed at the SetValue method, but never unboxed. OK, so let's try doing the boxing/unboxing ourselves.&lt;/p&gt;
&lt;pre&gt;&lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt; instance = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt;(10);
&lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(instance);

&lt;span class="type"&gt;Object&lt;/span&gt; objectInstance = instance;
&lt;span class="type"&gt;Type&lt;/span&gt; myType = &lt;span class="keyword"&gt;typeof&lt;/span&gt;(&lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt;);

&lt;span class="type"&gt;PropertyInfo&lt;/span&gt; propertyX = myType.GetProperty(&lt;span class="string"&gt;&amp;quot;X&amp;quot;&lt;/span&gt;);
propertyX.SetValue(objectInstance, 15, &lt;span class="keyword"&gt;null&lt;/span&gt;);
instance = (&lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt;)objectInstance;

&lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(instance);&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre class="console"&gt;X: 10
X: 15
Press any key to continue . . .&lt;/pre&gt;
&lt;p&gt;It works. That was the problem! I left it at that, but something still felt not quite right.&lt;/p&gt;
&lt;p&gt;What was really going on is that looking at the tree, I missed the forest. I saw reflection and thought that the underlying problem had to be reflection. Never stopped to think that when you pass a value type as a parameter the CLR sends a copy, and not the actual instance. The value of it was being set alright, but &lt;span class="b"&gt;to the copy &lt;/span&gt;and not to my instance. It was just the expected behavior, just like this:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;static void&lt;/span&gt; Main(&lt;span class="keyword"&gt;string&lt;/span&gt;[] args)
{
    &lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt; instance = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt;(10);
    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(instance);
    SetValueToStruct(instance);
    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(instance);
}

&lt;span class="keyword"&gt;static void&lt;/span&gt; SetValueToStruct(&lt;span class="type"&gt;UglyMutableStruct&lt;/span&gt; aCopy)
{
    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;   --- Start method's scope ---&amp;quot;&lt;/span&gt;);
    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;   {0}&amp;quot;&lt;/span&gt;, aCopy);
    aCopy.X = 15;
    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;   {0}&amp;quot;&lt;/span&gt;, aCopy);
    &lt;span class="type"&gt;Console&lt;/span&gt;.WriteLine(&lt;span class="string"&gt;&amp;quot;   --- End method's scope ---&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre class="console"&gt;X: 10
   --- Start method's scope --
   X: 10
   X: 15
   --- End method's scope --
X: 10
Press any key to continue . . .&lt;/pre&gt;
&lt;p&gt;The output is just as one would expect and it is exactly what was happening earlier.&lt;/p&gt;
&lt;p&gt;This is yet another reason why mutable structs are plain evil. Only use them when performance &lt;span class="b"&gt;is &lt;/span&gt;an issue.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;Random thoughts: &lt;/span&gt;Well, my first thought is why on earth would someone be using reflection on a known type? Someone may want to keep things as abstract as they can to lower coupling. This is if you know that sometime in the future the actual property setting will be on an unknown type, but still if that comes to happen, you will be handling an object anyways, wouldn't you? Another scenario would be setting a large amount of data (many properties) and you'd like to keep the code clean. Still having a large amount of data kind of defeats the whole purpose of using a struct. So my conclusion is that this scenario is not seen very often, and if it happens it probably means that you need to rethink your design rather than &lt;span class="b"&gt;make it work&lt;/span&gt;. But what's more important is that using mutable structs sooner or later means facing some &lt;span class="i"&gt;unexpected behavior&lt;/span&gt;. If you &lt;span class="i"&gt;have &lt;/span&gt;to use one, keep always in mind that you are.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1562048197280495196-1638429816909385968?l=fernandonicolet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fernandonicolet.blogspot.com/feeds/1638429816909385968/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fernandonicolet.blogspot.com/2009/05/evil-mutant-value-types.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/1638429816909385968'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/1638429816909385968'/><link rel='alternate' type='text/html' href='http://fernandonicolet.blogspot.com/2009/05/evil-mutant-value-types.html' title='Evil Mutant Value Types'/><author><name>Fernando Nicolet</name><uri>http://www.blogger.com/profile/04402615396818391251</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='27' height='32' src='http://3.bp.blogspot.com/_mmG4Sk1Z5oY/SgTqce9blEI/AAAAAAAAAAY/IazFgTXhp0U/S220/profile.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1562048197280495196.post-7876765431197437839</id><published>2009-05-16T03:08:00.004-03:00</published><updated>2009-07-12T17:38:01.351-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C# 4.0'/><category scheme='http://www.blogger.com/atom/ns#' term='Variance'/><title type='text'>Co-variance / Contra-variance - Part II</title><content type='html'>&lt;p&gt;This is a follow-up to my previous post: &lt;a href="http://blog.fernandonicolet.com/2009/05/co-variance-and-contra-variance-part-i.html"&gt;Co-variance / Contra-variance - Part I&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;On my previous post I used the unfortunate expression:&lt;/p&gt;
&lt;blockquote&gt;All this suffering will be finally put to an end once C# 4.0 comes out with the lovely new feature of safe Co- and Contra-variance.&lt;/blockquote&gt;
&lt;p&gt;As it turns out, this isn't entirely true. Sure, this new feature will definitely make like a lot easier but it will not give us a straight forward solution for the problems I stated. The main reason is that safe co- and contra-variance will be only applicable to interfaces and delegates due to a restriction in the CLR. I don't know what this restriction is but I'll promptly post it once I find it out. Another restriction is that safe variance can only be applied when there is a reference conversion between the generic arguments. This means that no variance will be possible between &lt;code&gt;int&lt;/code&gt; and &lt;code&gt;object&lt;/code&gt; and I suspect that it will not be possible between two types where an implicit cast operator is declared.&lt;/p&gt;
&lt;p&gt;Even though we cannot directly fix the methods on my previous post to work with safe variance, it can definitely be refactored into a safely variant solution. I will discuss how it would be achieved although for educational purposes I chose to implement something entirely new that is easier to understand and it's a better example of safe variance. Also I chose something different to what Mads Torgersen wrote for the &lt;i&gt;“New Features in C# 4.0”&lt;/i&gt; document in &lt;a href="http://code.msdn.microsoft.com/csharpfuture" target="_blanK"&gt;C# Future&lt;/a&gt;, to both train myself and to put a brand new example out there.&lt;/p&gt;
&lt;p&gt;So let's get our hands dirty:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public interface &lt;/span&gt;&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;TSource, TDestination&amp;gt;
{
    TDestination Convert(TSource source);
}&lt;/pre&gt;
&lt;p&gt;This interface can come in handy in lots of scenarios. Now we would like to implement a generic UI, so we may declare a form like this:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public partial class &lt;/span&gt;&lt;span class="type"&gt;MyGenericForm&lt;/span&gt;&amp;lt;TBusinessObject&amp;gt; : &lt;span class="type"&gt;Form&lt;/span&gt;
{

    &lt;span class="keyword"&gt;private &lt;/span&gt;&lt;span class="type"&gt;UserControl&lt;/span&gt; DisplayControl { &lt;span class="keyword"&gt;get&lt;/span&gt;; &lt;span class="keyword"&gt;set&lt;/span&gt;; }

    &lt;span class="keyword"&gt;public&lt;/span&gt; MyGenericForm()
    {
        FormBorderStyle = &lt;span class="type"&gt;FormBorderStyle&lt;/span&gt;.SizableToolWindow;

        InitializeComponent();
    }

    &lt;span class="keyword"&gt;public&lt;/span&gt; MyGenericForm(&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;TBusinessObject, &lt;span class="type"&gt;UserControl&lt;/span&gt;&amp;gt; converter, TBusinessObject sourceObject)
        :&lt;span class="keyword"&gt;this&lt;/span&gt;()
    {
        AsignSourceObject(converter, sourceObject);
    }

    &lt;span class="keyword"&gt;public void&lt;/span&gt; AsignSourceObject(&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;TBusinessObject, &lt;span class="type"&gt;UserControl&lt;/span&gt;&amp;gt; converter, TBusinessObject sourceObject)
    {
        &lt;span class="keyword"&gt;this&lt;/span&gt;.SuspendLayout();

        &lt;span class="keyword"&gt;if&lt;/span&gt; (DisplayControl != &lt;span class="keyword"&gt;null&lt;/span&gt;)
        {
            Controls.Remove(DisplayControl);
            DisplayControl.Dispose();
        }

        DisplayControl = converter.Convert(sourceObject);
        &lt;span class="keyword"&gt;this&lt;/span&gt;.Text = DisplayControl.Text;
        &lt;span class="keyword"&gt;this&lt;/span&gt;.ClientSize = DisplayControl.Size;
        &lt;span class="keyword"&gt;this&lt;/span&gt;.Controls.Add(DisplayControl);

        &lt;span class="keyword"&gt;this&lt;/span&gt;.ResumeLayout();
    }

    &lt;span class="keyword"&gt;private void&lt;/span&gt; CloseButton_Click(&lt;span class="keyword"&gt;object&lt;/span&gt; sender, &lt;span class="type"&gt;EventArgs&lt;/span&gt; e)
    {
        &lt;span class="keyword"&gt;this&lt;/span&gt;.Close();
    }

}&lt;/pre&gt;
&lt;p&gt;This form displays any kind of &lt;code&gt;TBusinessObject&lt;/code&gt; given that you implement an &lt;code&gt;IConverter&lt;/code&gt; that converts it to a &lt;code&gt;UserControl&lt;/code&gt;. So we implement the class &lt;code&gt;Person&lt;/code&gt;, &lt;code&gt;UserControlPerson&lt;/code&gt; and a converter between them:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;Person&lt;/span&gt;
{
    &lt;span class="keyword"&gt;public string&lt;/span&gt; UserName { &lt;span class="keyword"&gt;get&lt;/span&gt;; &lt;span class="keyword"&gt;set&lt;/span&gt;; }
    &lt;span class="keyword"&gt;public string&lt;/span&gt; FirstName { &lt;span class="keyword"&gt;get&lt;/span&gt;; &lt;span class="keyword"&gt;set&lt;/span&gt;; }
    &lt;span class="keyword"&gt;public string&lt;/span&gt; LastName { &lt;span class="keyword"&gt;get&lt;/span&gt;; &lt;span class="keyword"&gt;set&lt;/span&gt;; }
}

&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;PersonToUserControlConverter&lt;/span&gt; : &lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Person&lt;/span&gt;, &lt;span class="type"&gt;UserControl&lt;/span&gt;&amp;gt;
{
    &lt;span class="keyword"&gt;public &lt;/span&gt;&lt;span class="type"&gt;UserControl&lt;/span&gt; Convert(&lt;span class="type"&gt;Person&lt;/span&gt; source)
    {
        &lt;span class="type"&gt;PersonUserControl&lt;/span&gt; ctrl = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;PersonUserControl&lt;/span&gt;();
        ctrl.User = source;
        &lt;span class="keyword"&gt;return&lt;/span&gt; ctrl;
    }
}&lt;/pre&gt;
&lt;p&gt;Now we use the form like this:&lt;/p&gt;
&lt;pre&gt;&lt;span class="type"&gt;Person&lt;/span&gt; john = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;Person&lt;/span&gt;() { UserName = &lt;span class="string"&gt;&amp;quot;Johnny&amp;quot;&lt;/span&gt;, FirstName = &lt;span class="string"&gt;&amp;quot;John&amp;quot;&lt;/span&gt;, LastName = &lt;span class="string"&gt;&amp;quot;Doe&amp;quot;&lt;/span&gt; };
&lt;span class="keyword"&gt;using&lt;/span&gt; (&lt;span class="type"&gt;MyGenericForm&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Person&lt;/span&gt;&amp;gt; frm = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;MyGenericForm&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Person&lt;/span&gt;&amp;gt;(&lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;PersonToUserControlConverter&lt;/span&gt;(), john))
{
    frm.ShowDialog();
}&lt;/pre&gt;
&lt;p&gt;Cool, it works as expected.&lt;/p&gt;
&lt;p&gt;Further on the development of my project, I found myself needing a new form with some other features and not as restrictive as this one. I make it.&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public partial class &lt;/span&gt;&lt;span class="type"&gt;AnotherGenericForm&lt;/span&gt;&amp;lt;TBusinessObject&amp;gt; : &lt;span class="type"&gt;Form&lt;/span&gt;
{
    &lt;span class="keyword"&gt;public&lt;/span&gt; AnotherGenericForm()
    {
        InitializeComponent();
    }

    &lt;span class="comment"&gt;// Form's code&lt;/span&gt;

    &lt;span class="keyword"&gt;public void&lt;/span&gt; AsignSourceObject(&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;TBusinessObject, &lt;span class="type"&gt;Control&lt;/span&gt;&amp;gt; converter, TBusinessObject sourceObject)
    {
        &lt;span class="comment"&gt;// Some code&lt;/span&gt;
    }

    &lt;span class="comment"&gt;// More code&lt;/span&gt;

}&lt;/pre&gt;
&lt;p&gt;Unfortunately I can't use &lt;code&gt;PersonToUserControl&lt;/code&gt; converter since it doesn't implement the &lt;code&gt;IConverter&amp;lt;TBusinessObject, Control&amp;gt;&lt;/code&gt; interface. No problem, I'll just declare it and explicitly implement it:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;PersonToUserControlConverter&lt;/span&gt;
    : &lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Person&lt;/span&gt;, &lt;span class="type"&gt;UserControl&lt;/span&gt;&amp;gt;, &lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Person&lt;/span&gt;, &lt;span class="type"&gt;Control&lt;/span&gt;&amp;gt;
{
    &lt;span class="keyword"&gt;public &lt;/span&gt;&lt;span class="type"&gt;UserControl&lt;/span&gt; Convert(&lt;span class="type"&gt;Person&lt;/span&gt; source)
    {
        &lt;span class="type"&gt;PersonUserControl&lt;/span&gt; ctrl = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;PersonUserControl&lt;/span&gt;();
        ctrl.User = source;
        &lt;span class="keyword"&gt;return&lt;/span&gt; ctrl;
    }

    &lt;span class="type"&gt;Control IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Person&lt;/span&gt;, &lt;span class="type"&gt;Control&lt;/span&gt;&amp;gt;.Convert(&lt;span class="type"&gt;Person&lt;/span&gt; source)
    {
        &lt;span class="keyword"&gt;return this&lt;/span&gt;.Convert(source);
    }
}&lt;/pre&gt;
&lt;p&gt;OK, suddenly I realize the following: Eventually I may need to implement &lt;code&gt;IConverter&amp;lt;TBusinessObject, ScrollableControl&amp;gt;&lt;/code&gt; and who knows what else. It seems that this will come back to haunt me. This isn't the best course of action.&lt;/p&gt;
&lt;p&gt;The solution: &lt;span class="b"&gt;Co-Variance.&lt;/span&gt;&lt;br/&gt;
With C# 4.0 I can make the &lt;code&gt;IConverter&lt;/code&gt; interface co-variant. How? Using the &lt;code class="b"&gt;out&lt;/code&gt; keyword.&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public interface &lt;/span&gt;&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;TSource, &lt;span class="keyword"&gt;out&lt;/span&gt; TDestination&amp;gt;
{
    TDestination Convert(TSource source);
}&lt;/pre&gt;
&lt;p&gt;Declaring the interface in this manner makes it safely co-variant. The &lt;code&gt;out&lt;/code&gt; keyword indicates that &lt;code&gt;TDestination&lt;/code&gt; can only be in an output position. Now &lt;code&gt;IConverter&amp;lt;Person, UserControl&amp;gt;&lt;/code&gt; is also considered as &lt;code&gt;IConverter&amp;lt;Person, ContainerControl&amp;gt;&lt;/code&gt;and all the way up the inheritance chain up to &lt;code&gt;IConverter&amp;lt;Person, Object&amp;gt;&lt;/code&gt;. Notice that no breaking changes are introduced and we can now safely use our converter in the new form. Now we can safely declare:&lt;/p&gt;
&lt;pre&gt;&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Person&lt;/span&gt;, &lt;span class="type"&gt;Control&lt;/span&gt;&amp;gt; converter = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;PersonToUserControlConverter&lt;/span&gt;();&lt;/pre&gt;
&lt;p&gt;In a similar fashion, we might end up having a form that has the following method:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public void&lt;/span&gt; AsignSourceObject(&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;ForumUser&lt;/span&gt;, &lt;span class="type"&gt;Control&lt;/span&gt;&amp;gt; converter, TBusinessObject sourceObject)
{
    &lt;span class="comment"&gt;// Some code&lt;/span&gt;
}&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;ForumUser&lt;/code&gt; inherits from &lt;code&gt;User&lt;/code&gt;. We can't use the same approach because in our interface &lt;code&gt;TSource&lt;/code&gt; is an input. Also covariance goes up the inheritance chain, not downwards.&lt;/p&gt;
&lt;p&gt;The solution: &lt;span class="b"&gt;Contra-variance.&lt;/span&gt;&lt;br/&gt;
As you have already guessed, contra-variance and the &lt;code class="b"&gt;in&lt;/code&gt; keyword will help us out here. Our (hopefully) final declaration of our &lt;code&gt;IConverter&lt;/code&gt; is:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public interface &lt;/span&gt;&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; TSource, &lt;span class="keyword"&gt;out&lt;/span&gt; TDestination&amp;gt;
{
    TDestination Convert(TSource source);
}&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;in&lt;/code&gt; keyword indicates that &lt;code&gt;TSource&lt;/code&gt; can only be in an input position. Now &lt;code&gt;IConverter&amp;lt;Person, UserControl&amp;gt;&lt;/code&gt; is also considered as &lt;code&gt;IConverter&amp;lt;ForumUser, UserControl&amp;gt;&lt;/code&gt; and any other inheritance ramifications of &lt;code&gt;Person&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Now, all of the following is completely legal:&lt;/p&gt;
&lt;pre&gt;&lt;span class="type"&gt;PersonToUserControlConverter&lt;/span&gt; converter = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;PersonToUserControlConverter&lt;/span&gt;();

&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;ForumUser&lt;/span&gt;, &lt;span class="type"&gt;Control&lt;/span&gt;&amp;gt; forumUserToControl = converter;
&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;ForumUser&lt;/span&gt;, &lt;span class="type"&gt;UserControl&lt;/span&gt;&amp;gt; forumUserToUserControl = converter;
&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;ForumAdministrator&lt;/span&gt;, &lt;span class="type"&gt;ContainerControl&lt;/span&gt;&amp;gt; forumUserToControl = converter;
&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Person&lt;/span&gt;, &lt;span class="keyword"&gt;object&lt;/span&gt;&amp;gt; forumUserToControl = converter;
&lt;span class="type"&gt;IConverter&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Person&lt;/span&gt;, &lt;span class="type"&gt;IComponent&lt;/span&gt;&amp;gt; forumUserToControl = converter;&lt;/pre&gt;
&lt;p&gt;Notice the last declaration. Even though &lt;code&gt;IComponent&lt;/code&gt; isn't exactly in the inheritance chain, &lt;code&gt;UserControl&lt;/code&gt; implements it, so it's legal too.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;Why the in/out keywords?&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Well, the obvious answer is &lt;code&gt;out&lt;/code&gt; for output position and &lt;code&gt;in&lt;/code&gt; for input position. Well… duh! But why is co-variance allowed only through arguments in output position? Well, if you think about it, it makes sense. Consider the following classes:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;A&lt;/span&gt; { }
&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;B&lt;/span&gt; : &lt;span class="type"&gt;A&lt;/span&gt; { }
&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;C&lt;/span&gt; : &lt;span class="type"&gt;A&lt;/span&gt; { }
&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;D&lt;/span&gt; : &lt;span class="type"&gt;C&lt;/span&gt; { }
&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;E&lt;/span&gt; : &lt;span class="type"&gt;C&lt;/span&gt; { }&lt;/pre&gt;
&lt;p&gt;Now, if we have a method that returns a C we are certain that we can treat it as an A. We don't know if we can treat him as D since it might be a C, D or E. Hence, it is co-variant. Now if the object was to be used as a method's parameter, it means the method needs a C. So we can feed that method anything that can be considered a C, like D or E. We can't feed it with an A or a B since they cannot be used as a C. Hence, it is contra-variant. My head hurts.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;Co- and Contra-variant Types in .NET Framework 4.0&lt;/span&gt;&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public interface &lt;/span&gt;&lt;span class="type"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;out&lt;/span&gt; T&amp;gt; : &lt;span class="type"&gt;IEnumerable&lt;/span&gt;
{
    &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;IEnumerator&lt;/span&gt;&amp;lt;T&amp;gt; GetEnumerator();
}

&lt;span class="keyword"&gt;public interface &lt;/span&gt;&lt;span class="type"&gt;IEnumerator&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;out&lt;/span&gt; T&amp;gt; : &lt;span class="type"&gt;IEnumerator&lt;/span&gt;, &lt;span class="type"&gt;IDisposable&lt;/span&gt;
{
    &lt;span class="keyword"&gt;new&lt;/span&gt; T Current { &lt;span class="keyword"&gt;get&lt;/span&gt;; }
}

&lt;span class="keyword"&gt;public interface &lt;/span&gt;&lt;span class="type"&gt;IComparer&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T&amp;gt;
{
    &lt;span class="keyword"&gt;int&lt;/span&gt; Compare(T x, T y);
}

&lt;span class="keyword"&gt;public delegate&lt;/span&gt; TResult &lt;span class="type"&gt;Func&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;out&lt;/span&gt; TResult&amp;gt;();
&lt;span class="keyword"&gt;public delegate&lt;/span&gt; TResult &lt;span class="type"&gt;Func&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T, &lt;span class="keyword"&gt;out&lt;/span&gt; TResult&amp;gt;(T arg);
&lt;span class="keyword"&gt;public delegate&lt;/span&gt; TResult &lt;span class="type"&gt;Func&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T1, &lt;span class="keyword"&gt;in&lt;/span&gt; T2, &lt;span class="keyword"&gt;out&lt;/span&gt; TResult&amp;gt;(T1 arg1, T2 arg2);
&lt;span class="keyword"&gt;public delegate&lt;/span&gt; TResult &lt;span class="type"&gt;Func&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T1, &lt;span class="keyword"&gt;in&lt;/span&gt; T2, &lt;span class="keyword"&gt;in&lt;/span&gt; T3, &lt;span class="keyword"&gt;out&lt;/span&gt; TResult&amp;gt;(T1 arg1, T2 arg2, T3 arg3);
&lt;span class="keyword"&gt;public delegate&lt;/span&gt; TResult &lt;span class="type"&gt;Func&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T1, &lt;span class="keyword"&gt;in&lt;/span&gt; T2, &lt;span class="keyword"&gt;in&lt;/span&gt; T3, &lt;span class="keyword"&gt;in&lt;/span&gt; T4, &lt;span class="keyword"&gt;out&lt;/span&gt; TResult&amp;gt;(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
&lt;span class="keyword"&gt;public delegate void &lt;/span&gt;&lt;span class="type"&gt;Action&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T&amp;gt;(T arg);
&lt;span class="keyword"&gt;public delegate void &lt;/span&gt;&lt;span class="type"&gt;Action&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T1, &lt;span class="keyword"&gt;in&lt;/span&gt; T2&amp;gt;(T1 arg1, T2 arg2);
&lt;span class="keyword"&gt;public delegate void &lt;/span&gt;&lt;span class="type"&gt;Action&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T1, &lt;span class="keyword"&gt;in&lt;/span&gt; T2, &lt;span class="keyword"&gt;in&lt;/span&gt; T3&amp;gt;(T1 arg1, T2 arg2, T3 arg3);
&lt;span class="keyword"&gt;public delegate void &lt;/span&gt;&lt;span class="type"&gt;Action&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T1, &lt;span class="keyword"&gt;in&lt;/span&gt; T2, &lt;span class="keyword"&gt;in&lt;/span&gt; T3, &lt;span class="keyword"&gt;in&lt;/span&gt; T4&amp;gt;(T1 arg1, T2 arg2, T3 arg3, T4 arg4);&lt;/pre&gt;
&lt;p&gt;A couple of educated guesses:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public interface &lt;/span&gt;&lt;span class="type"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T&amp;gt;
{
    &lt;span class="comment"&gt;// Members&lt;/span&gt;
}

&lt;span class="keyword"&gt;public interface &lt;/span&gt;&lt;span class="type"&gt;IGrouping&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;out&lt;/span&gt; TKey, &lt;span class="keyword"&gt;out&lt;/span&gt; TElement&amp;gt;
{
    &lt;span class="comment"&gt;// Members&lt;/span&gt;
}

&lt;span class="keyword"&gt;public interface &lt;/span&gt;&lt;span class="type"&gt;IQueryable&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;out&lt;/span&gt; TElement&amp;gt;
{
    &lt;span class="comment"&gt;// Members&lt;/span&gt;
}

&lt;span class="keyword"&gt;public delegate void &lt;/span&gt;&lt;span class="type"&gt;EventHandler&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; TEventArgs&amp;gt;(&lt;span class="keyword"&gt;object&lt;/span&gt; sender, TEventArgs e);
&lt;span class="keyword"&gt;public delegate bool &lt;/span&gt;&lt;span class="type"&gt;Predicate&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T&amp;gt;(T obj);
&lt;span class="keyword"&gt;public delegate int &lt;/span&gt;&lt;span class="type"&gt;Comparison&lt;/span&gt;&amp;lt;&lt;span class="keyword"&gt;in&lt;/span&gt; T&amp;gt;(T x, T y);&lt;/pre&gt;
&lt;p&gt;&lt;span class="b"&gt;Solution to Previous Post&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;I'm not going to go into details about the solution. To the co-variance problem, well the solution is pretty straight forward. We change the &lt;code&gt;SafeMethod&lt;/code&gt; to have an &lt;code&gt;IEnumerable&amp;lt;MyBase&amp;gt;&lt;/code&gt; as parameter. Just like that we could now feed it with a &lt;code&gt;List&amp;lt;MyFirstDerived&amp;gt;&lt;/code&gt; without any problems.&lt;/p&gt;
&lt;p&gt;The contra-variant problem is not that simple. One possible solution would involve defining our own interface and class:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public interface &lt;/span&gt;&lt;span class="type"&gt;ICollectable&lt;/span&gt;&amp;lt;T&amp;gt; 
{

    &lt;span class="keyword"&gt;int&lt;/span&gt; Count { &lt;span class="keyword"&gt;get&lt;/span&gt;; }
    &lt;span class="keyword"&gt;void&lt;/span&gt; Add(T item);
    &lt;span class="keyword"&gt;void&lt;/span&gt; Insert(&lt;span class="keyword"&gt;int&lt;/span&gt; index, T item);
    &lt;span class="keyword"&gt;bool&lt;/span&gt; Remove(T item);
    &lt;span class="keyword"&gt;void&lt;/span&gt; RemoveAt(&lt;span class="keyword"&gt;int&lt;/span&gt; index);
    &lt;span class="keyword"&gt;void&lt;/span&gt; Clear();
    &lt;span class="keyword"&gt;bool&lt;/span&gt; Contains(T item);

}

&lt;span class="keyword"&gt;public partial class &lt;/span&gt;&lt;span class="type"&gt;Pack&lt;/span&gt;&amp;lt;TAnimal&amp;gt;: &lt;span class="type"&gt;IList&lt;/span&gt;&amp;lt;TAnimal&amp;gt;, &lt;span class="type"&gt;ICollectable&lt;/span&gt;&amp;lt;TAnimal&amp;gt;, &lt;span class="type"&gt;IList&lt;/span&gt;
    &lt;span class="keyword"&gt;where&lt;/span&gt; TAnimal : &lt;span class="type"&gt;Animal&lt;/span&gt;
{

    &lt;span class="keyword"&gt;private &lt;/span&gt;&lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;TAnimal&amp;gt; innerList;

    &lt;span class="comment"&gt;// A whole lot of delegations!&lt;/span&gt;

}&lt;/pre&gt;
&lt;p&gt;Actually, I'd take it a little further and remove the &lt;code&gt;Animal&lt;/code&gt; restriction to create yet another generic collection. The &lt;code&gt;ICollectable&lt;/code&gt; gives you an interface of a collection where you can blindly modify it. Pretty weird, huh? Anyways, now our &lt;code&gt;AddTigerToPack&lt;/code&gt; method would receive an &lt;code&gt;ICollectable&amp;lt;Tiger&amp;gt;&lt;/code&gt; and our &lt;code&gt;Pack&amp;lt;Animals&amp;gt;&lt;/code&gt; will be considered as such thanks to safe contra-variance.&lt;/p&gt;
&lt;p&gt;&lt;span class="b"&gt;Random thoughts:  &lt;/span&gt;I wonder if they would include a better named &lt;code&gt;ICollectable&amp;lt;in T&amp;gt;&lt;/code&gt; interface… Seriously, it keeps marveling me how they manage to keep introducing major changes without breaking any existing code. They manage to add a wonderful new functionality which opens a lot of possibilities without restricting what we already had. All these while still keeping things strongly typed and relatively simple. Kudos!&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1562048197280495196-7876765431197437839?l=fernandonicolet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fernandonicolet.blogspot.com/feeds/7876765431197437839/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fernandonicolet.blogspot.com/2009/05/co-variance-contra-variance-part-ii.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/7876765431197437839'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/7876765431197437839'/><link rel='alternate' type='text/html' href='http://fernandonicolet.blogspot.com/2009/05/co-variance-contra-variance-part-ii.html' title='Co-variance / Contra-variance - Part II'/><author><name>Fernando Nicolet</name><uri>http://www.blogger.com/profile/04402615396818391251</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='27' height='32' src='http://3.bp.blogspot.com/_mmG4Sk1Z5oY/SgTqce9blEI/AAAAAAAAAAY/IazFgTXhp0U/S220/profile.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1562048197280495196.post-4212537778663486592</id><published>2009-05-10T14:45:00.020-03:00</published><updated>2009-07-12T17:37:56.295-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C# 4.0'/><category scheme='http://www.blogger.com/atom/ns#' term='Variance'/><title type='text'>Co-variance / Contra-variance - Part I</title><content type='html'>&lt;p&gt;Apparently, one common mistake made by C# programmers involves co-variance and contra-variance. Among the &lt;i&gt;cross-thread operation not valid&lt;/i&gt; exception and inter-form communication, one of the most common questions seen on the Microsoft's Visual C# Forum is why a &lt;code&gt;List&amp;lt;MyDerivedType&amp;gt;&lt;/code&gt; can't be cast to a &lt;code&gt;List&amp;lt;MyBaseType&amp;gt;&lt;/code&gt;. I must confess that the first time encountered this problem I was both surprised and pissed. In time I learned that when the language doesn't allow you to perform some kind of action, there is a good reason behind it. Soon enough I realized that this wasn't the exception.&lt;/p&gt;
&lt;p&gt;Take into consideration the following code:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;MyBase&lt;/span&gt;
{
    &lt;span class="keyword"&gt;public virtual void&lt;/span&gt; Operation()
    {
        &lt;span class="comment"&gt;// Some code.&lt;/span&gt;
    }
}

&lt;span class="keyword"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;MyFirstDerived &lt;/span&gt;: &lt;span class="type"&gt;MyBase&lt;/span&gt;
{
    &lt;span class="keyword"&gt;public override void&lt;/span&gt; Operation()
    {
        &lt;span class="comment"&gt;// Some code.&lt;/span&gt;
    }
}

&lt;span class="keyword"&gt;public class&lt;/span&gt; &lt;span class="type"&gt;MySecondDerived&lt;/span&gt; : &lt;span class="type"&gt;MyBase&lt;/span&gt;
{
    &lt;span class="keyword"&gt;public override void &lt;/span&gt;Operation()
    {
        &lt;span class="comment"&gt;// Some code.&lt;/span&gt;
    }
}

&lt;span class="keyword"&gt;class&lt;/span&gt; &lt;span class="type"&gt;Program&lt;/span&gt;
{
    &lt;span class="keyword"&gt;static void&lt;/span&gt; Main(&lt;span class="keyword"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span class="type"&gt;IList&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;MyFirstDerived&lt;/span&gt;&amp;gt; myStronglyTypedList = &lt;span class="keyword"&gt;new&lt;/span&gt; &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;MyFirstDerived&lt;/span&gt;&amp;gt;();
        BlowUpMethod(myStronglyTypedList);
        SafeMethod(myStronglyTypedList);
    }

    &lt;span class="keyword"&gt;static void&lt;/span&gt; BlowUpMethod(&lt;span class="type"&gt;IList&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;MyBase&lt;/span&gt;&amp;gt; aNotSoStronglyTypedList)
    {
        aNotSoStronglyTypedList.Add(&lt;span class="keyword"&gt;new&lt;/span&gt; &lt;span class="type"&gt;MySecondDerived&lt;/span&gt;());
    }

    &lt;span class="keyword"&gt;static void &lt;/span&gt;SafeMethod(&lt;span class="type"&gt;IList&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;MyBase&lt;/span&gt;&amp;gt; aNotSoStronglyTypedList)
    {
        &lt;span class="keyword"&gt;foreach &lt;/span&gt;(&lt;span class="type"&gt;MyBase&lt;/span&gt; aBaseObject &lt;span class="keyword"&gt;in &lt;/span&gt;aNotSoStronglyTypedList)
        {
            aBaseObject.Operation();
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Since C#, up to version 3.0, is invariant this code does not compile. One of the errors states:&lt;/p&gt;
&lt;blockquote&gt;Argument '1': cannot convert from 'System.Collections.Generic.IList&amp;lt;CoVarianceContraVariance.MyFirstDerived&amp;gt;' to 'System.Collections.Generic.IList&amp;lt;CoVarianceContraVariance.MyBase&amp;gt;'&lt;/blockquote&gt;
&lt;p&gt;If it did work, in &lt;code&gt;SafeMethod&lt;/code&gt; there would no issues at all. This would work without any undesired secondary effects. This behavior is called co-variance. On the other hand, after invoking the &lt;code&gt;BlowUpMethod&lt;/code&gt; we would have a &lt;code&gt;MySecondDerived&lt;/code&gt; instance in a list were only &lt;code&gt;MyFirstDerived&lt;/code&gt; (and derivations) instances are allowed. This will defeat the whole purpose of having strongly typed lists, wouldn't it?&lt;/p&gt;
&lt;p&gt;Fortunately, there is a workaround to allow some sort of co-variance behavior that I find extremely useful in some scenarios.&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;static void &lt;/span&gt;SafeMethod&amp;lt;T&amp;gt;(&lt;span class="type"&gt;IList&lt;/span&gt;&amp;lt;T&amp;gt; aStronglyTypedList) &lt;span class="keyword"&gt;where &lt;/span&gt;T : &lt;span class="type"&gt;MyBase&lt;/span&gt;
{
    &lt;span class="keyword"&gt;foreach &lt;/span&gt;(&lt;span class="type"&gt;MyBase &lt;/span&gt;aBaseObject &lt;span class="keyword"&gt;in &lt;/span&gt;aStronglyTypedList)
    {
        aBaseObject.Operation();
    }
}&lt;/pre&gt;
&lt;p&gt;Works like a charm!&lt;/p&gt;
&lt;p&gt;As you would expect a similar problems occurs when trying to apply contra-variance, but it is in fact a little trickier:&lt;/p&gt;
&lt;pre&gt;&lt;span class="keyword"&gt;public abstract class &lt;/span&gt;&lt;span class="type"&gt;Animal &lt;/span&gt;{}
&lt;span class="keyword"&gt;public abstract class &lt;/span&gt;&lt;span class="type"&gt;Carnivore &lt;/span&gt;: &lt;span class="type"&gt;Animal&lt;/span&gt;
{
    &lt;span class="keyword"&gt;public void &lt;/span&gt;Hunt (&lt;span class="type"&gt;Animal &lt;/span&gt;prey)
    {
        &lt;span class="comment"&gt;// Some code.&lt;/span&gt;
    }
}
&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;Tiger&lt;/span&gt; : &lt;span class="type"&gt;Carnivore&lt;/span&gt; { }
&lt;span class="keyword"&gt;public abstract class &lt;/span&gt;&lt;span class="type"&gt;Herbivore&lt;/span&gt; : &lt;span class="type"&gt;Animal&lt;/span&gt; { }
&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;Antelope&lt;/span&gt; : &lt;span class="type"&gt;Herbivore&lt;/span&gt; { }

&lt;span class="keyword"&gt;public class &lt;/span&gt;&lt;span class="type"&gt;Program&lt;/span&gt;
{
    &lt;span class="keyword"&gt;static void &lt;/span&gt;Main(&lt;span class="keyword"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Animal&lt;/span&gt;&amp;gt; animals = &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Animal&lt;/span&gt;&amp;gt;()
        {
            &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;Antelope&lt;/span&gt;(),
            &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;Tiger&lt;/span&gt;()
        };
        HuntingOverkill(animals, &lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;Antelope&lt;/span&gt;());
        AddTigerToPack(animals);
    }

    &lt;span class="keyword"&gt;static void &lt;/span&gt;HuntingOverkill(&lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Carnivore&lt;/span&gt;&amp;gt; packOfCarnivores, &lt;span class="type"&gt;Animal &lt;/span&gt;prey)
    {
        &lt;span class="keyword"&gt;foreach &lt;/span&gt;(&lt;span class="type"&gt;Carnivore &lt;/span&gt;carnivore &lt;span class="keyword"&gt;in &lt;/span&gt;packOfCarnivores)
        {
            carnivore.Hunt(prey);
        }
    }

    &lt;span class="keyword"&gt;static void &lt;/span&gt;AddTigerToPack(&lt;span class="type"&gt;List&lt;/span&gt;&amp;lt;&lt;span class="type"&gt;Tiger&lt;/span&gt;&amp;gt; registeredTigers)
    {
        registeredTigers.Add(&lt;span class="keyword"&gt;new &lt;/span&gt;&lt;span class="type"&gt;Tiger&lt;/span&gt;());
    }
}&lt;/pre&gt;
&lt;p&gt;Again, this code will not compile since a list of animals cannot be converted to a list of tigers. If it did, the method &lt;code&gt;HuntingOverkill&lt;/code&gt; would be making a defenseless antelope hunt, and that is why this isn't allowed, although the method &lt;code&gt;AddTigerToPack&lt;/code&gt; could work without any problems.&lt;/p&gt;
&lt;p&gt;A similar workaround could be tried here, but it wouldn't work either, since if we made &lt;code&gt;registeredTigers&lt;/code&gt; a list of T with T inheriting from &lt;code&gt;Animal&lt;/code&gt;, we could end up with a &lt;code&gt;Tiger&lt;/code&gt; inside a pack of herbivores. Those poor little creatures, can you imagine the chaos? So I tried to work up some workaround for this too, but although I tried banging my head with the keyboard, I couldn't come up with one that looked cool. I only ended up with ugly methods with generic arguments with lots of constraints and that couldn't be inferred by the compiler when calling them.&lt;/p&gt;
&lt;p&gt;All this suffering will be finally put to an end once C# 4.0 comes out with the lovely new feature of safe Co- and Contra-variance. I will elaborate on how it will work on my next post.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Random thoughts: &lt;/b&gt;One could possible ask why the C# compiler isn't smart enough to allow cases like &lt;code&gt;SafeMethod&lt;/code&gt; or &lt;code&gt;AddTigerToPack&lt;/code&gt;. Well, first of all, I wouldn't like the compiler looking so deep into my code before compiling. A line has to be drawn at some point and I think this goes far beyond that line. Also this example is pretty simple and this cases of variance can (and will) end up in much more complex code. It will end up making the compiler having to do an awful lot of work and it would take huge amount of time in big projects. Finally and most importantly, changing something that is completely legal inside the method's scope would introduce breaking changes! It can even cause an application using our class library to stop working. So no, this is completely out of the question.&lt;/p&gt;
&lt;p&gt;Follow-up: &lt;a href="http://blog.fernandonicolet.com/2009/05/co-variance-contra-variance-part-ii.html"&gt;Co-variance / Contra-variance - Part II&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/1562048197280495196-4212537778663486592?l=fernandonicolet.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://fernandonicolet.blogspot.com/feeds/4212537778663486592/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://fernandonicolet.blogspot.com/2009/05/co-variance-and-contra-variance-part-i.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/4212537778663486592'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1562048197280495196/posts/default/4212537778663486592'/><link rel='alternate' type='text/html' href='http://fernandonicolet.blogspot.com/2009/05/co-variance-and-contra-variance-part-i.html' title='Co-variance / Contra-variance - Part I'/><author><name>Fernando Nicolet</name><uri>http://www.blogger.com/profile/04402615396818391251</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='27' height='32' src='http://3.bp.blogspot.com/_mmG4Sk1Z5oY/SgTqce9blEI/AAAAAAAAAAY/IazFgTXhp0U/S220/profile.jpg'/></author><thr:total>0</thr:total></entry></feed>
