<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://msmvps.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>the blog =&gt; anything goes : software C# language</title><link>http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx</link><description>Tags: software C# language</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><item><title>Confusion++</title><link>http://msmvps.com/blogs/senthil/archive/2009/02/26/confusion.aspx</link><pubDate>Thu, 26 Feb 2009 13:09:44 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1674077</guid><dc:creator>Senthil</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1674077</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1674077</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2009/02/26/confusion.aspx#comments</comments><description>&lt;p&gt;I&amp;#39;ll bet a hundred bucks that any entry level C++ interview or exam will somehow drift into questions about the pre and post increment operators. It&amp;#39;s almost become a canonical, rite of passage sort of thing.&lt;/p&gt; &lt;p&gt;Now using the operators is one thing, overloading them for your own types is another. In C++, you write something like&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;X {
    &lt;span style="color:blue;"&gt;int &lt;/span&gt;val;
&lt;span style="color:blue;"&gt;public&lt;/span&gt;:

    X() : val(0){ }

    X &lt;span style="color:blue;"&gt;operator&lt;/span&gt;++() { val++; &lt;span style="color:blue;"&gt;return &lt;/span&gt;*&lt;span style="color:blue;"&gt;this&lt;/span&gt;; }
    X &lt;span style="color:blue;"&gt;operator&lt;/span&gt;++(&lt;span style="color:blue;"&gt;int&lt;/span&gt;) { X pX = *&lt;span style="color:blue;"&gt;this&lt;/span&gt;; val++; &lt;span style="color:blue;"&gt;return &lt;/span&gt;pX; };

    &lt;span style="color:blue;"&gt;int &lt;/span&gt;Value() { &lt;span style="color:blue;"&gt;return &lt;/span&gt;val; }
};&lt;/pre&gt;
&lt;p&gt;Fairly straightforward stuff - C++ uses the int overload to distinguish between pre and post, and the post increment overload copies itself before incrementing and returns the copy.&lt;/p&gt;
&lt;p&gt;Now let&amp;#39;s see how to do this in C#.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;X
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public int &lt;/span&gt;Value { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;&lt;span style="color:blue;"&gt;operator &lt;/span&gt;++(&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;p)
    {
        &lt;span style="color:blue;"&gt;int &lt;/span&gt;x = p.Value;
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;X&lt;/span&gt;() { Value = x + 1 };
    }
}&lt;/pre&gt;
&lt;p&gt;No, there&amp;#39;s no separate overload for the other one - the same method works for both pre and post increment operations. The compiler does the work of generating code that exhibits correct pre and post increment behavior. For code like&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;x = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;X&lt;/span&gt;();&lt;br /&gt;&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;y = x++;&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;it generates&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;x = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;X&lt;/span&gt;();
&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;y = x;
x = &lt;span style="color:#2b91af;"&gt;X&lt;/span&gt;.op_Increment(x);&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;and for code like&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;x = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;X&lt;/span&gt;();&lt;br /&gt;&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;y = ++x;&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;it generates&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;x = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;X&lt;/span&gt;();
&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;y = x = &lt;span style="color:#2b91af;"&gt;X&lt;/span&gt;.op_Increment(x);&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Nifty, eh?&lt;/p&gt;
&lt;p&gt;But wait, did you notice the difference between the C++ and C# overload implementation? The C# overload does not modify the original at all and always returns a copy, whereas the C++ code always modifies the current instance and returns a copy only for the post increment overload. Looking at the generated code, it should be easy to understand why - the compiler can&amp;#39;t do its magic if the overload tinkers with the original instance.&lt;/p&gt;
&lt;p&gt;Did you notice that X is a reference type?&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:#2b91af;"&gt;X &lt;/span&gt;x = &lt;span style="color:blue;"&gt;new&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;X&lt;/span&gt;();&lt;br /&gt;&lt;span style="color:#2b91af;"&gt;X&lt;/span&gt;y = x;&lt;br /&gt;&lt;br /&gt;x++;&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Given that x and y are referring to the same object after executing the second line, shouldn&amp;#39;t the increment be visible from y as well? It doesn&amp;#39;t happen though, because the overload returns a new instance that then gets assigned to x, leaving y referring to the &amp;quot;old&amp;quot; unmodified instance.&lt;/p&gt;
&lt;p&gt;All this confusion will not arise if X is a value type. The assignment of x to y will create a copy, so there&amp;#39;s no possibility of changes in x reflecting in y. And modifying the passed instance from within the operator overload will have no effect on the original instance either.&lt;/p&gt;
&lt;p&gt; Moral of the story : watch out when overloading operators on reference types.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1674077" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/C_2300_/default.aspx">C#</category></item><item><title>One of those 'doh' moments</title><link>http://msmvps.com/blogs/senthil/archive/2009/01/25/one-of-those-doh-moments.aspx</link><pubDate>Sun, 25 Jan 2009 20:22:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1665915</guid><dc:creator>Senthil</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1665915</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1665915</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2009/01/25/one-of-those-doh-moments.aspx#comments</comments><description>&lt;p&gt;There are times when you feel really proud of yourselves; on top of the world, with no one in sight. And then there are times when you can&amp;#39;t believe you did what you just did. Here&amp;#39;s one of the latter :-&lt;/p&gt;
&lt;p&gt; My task was to show a progress bar in our application. Nothing fancy there - just division of the operations to be performed into equal size chunks and &lt;span style="color:#800000;"&gt;Increment&lt;/span&gt;ing after completion of each task. Very straightforward indeed. &lt;/p&gt;
&lt;pre class="code"&gt;	&lt;span style="color:blue;"&gt;int &lt;/span&gt;increment;&lt;br /&gt;&lt;br /&gt;        &lt;span style="color:blue;"&gt;private void &lt;/span&gt;Form_Load(&lt;span style="color:blue;"&gt;object &lt;/span&gt;sender, &lt;span style="color:#2b91af;"&gt;EventArgs &lt;/span&gt;e)&lt;br /&gt;        {&lt;br /&gt;            &lt;span style="color:blue;"&gt;int &lt;/span&gt;discreteOperationsCount = GetDiscreteOperationsCount();&lt;br /&gt;            increment = (int)&lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.Ceil((&lt;span style="color:blue;"&gt;double&lt;/span&gt;)progressBar.Maximum / discreteOperationsCount);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        &lt;span style="color:blue;"&gt;private void &lt;/span&gt;OperationCompleted()&lt;br /&gt;        {&lt;br /&gt;            progressBar.Increment(increment);&lt;br /&gt;        }&lt;/pre&gt;
&lt;p&gt;It worked great when I tested it with 5, 10, 20 operations. I was even pleased that I cast the numerator to double straightaway, as I was typing code.&lt;/p&gt;
&lt;p&gt;Only until I found that the progress bar progresses too fast if the number of operations is more than 100. If the result of the division is less than 1, &lt;span style="color:#804040;"&gt;Math.Ceil&lt;/span&gt; pushes it up to 1, which means that the progress bar will be full when 100 (the default &lt;span style="color:#800000;"&gt;Maximum&lt;/span&gt; value) operations complete, regardless of the actual number of operations.&lt;/p&gt;
&lt;p&gt;&lt;b&gt;Doh.&lt;/b&gt;&lt;/p&gt;
&lt;p&gt;Ok, I thought, so let&amp;#39;s store increment as a double and call &lt;span style="color:#800000;"&gt;Increment&lt;/span&gt; with that number. It would have worked, but for the fact that Increment does not have any overloads - it only accepts an integer. Hmm.. what gives?&lt;/p&gt;
&lt;p&gt;After a little bit of thought, I figured out a way - scale everything by the degree of precision needed. With a scaling factor of 10, the calculation now becomes&lt;/p&gt;
&lt;pre class="code"&gt;increment = &lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.Ceil((&lt;span style="color:blue;"&gt;double&lt;/span&gt;)progressBar.Maximum / discreteOperationsCount * 10);&lt;/pre&gt;
&lt;p&gt;If discreteOperationsCount is 520, for example, then increment would become (100 * 10) / 520 * 10 = 19. We still have an integer, but it is more precise than the one calculated earlier.&lt;/p&gt;
&lt;p&gt;Of course, you could increase the scaling factor further, and the number of significant digits will also increase exponentially. But the progress bar will have to do some approximation when mapping progress to pixels on the screen, so beyond a point, the increase in precision doesn&amp;#39;t pay off that much.&lt;/p&gt;
&lt;p&gt;Like I said at the top of this post, I couldn&amp;#39;t believe I missed testing with the number of operations greater than the progress bar&amp;#39;s &lt;span style="color:#800000;"&gt;Maximum&lt;/span&gt;. Truly one of those &amp;#39;doh&amp;#39; moments.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1665915" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx">software</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category></item><item><title>The dangers of Thread.Abort</title><link>http://msmvps.com/blogs/senthil/archive/2008/12/17/the-dangers-of-thread-abort.aspx</link><pubDate>Wed, 17 Dec 2008 18:09:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1657017</guid><dc:creator>Senthil</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1657017</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1657017</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2008/12/17/the-dangers-of-thread-abort.aspx#comments</comments><description>&lt;p&gt;There have been a lot of &lt;a href="http://www.google.co.in/search?q=Thread.Abort+issue"&gt;blog posts&lt;/a&gt; about why calling Thread.Abort from one thread to abort another is a bad idea. If you&amp;#39;re still wondering if it actually is that bad, you&amp;#39;ll be convinced by the end of this blog post :).&lt;/p&gt;
&lt;p&gt;The other day, I was investigating frequent hangs in our application on the production machine. The only clue was that the last logged exception was a ThreadAbortException. What made it interesting was that in some cases, the application continued to run fine after logging the exception.&amp;nbsp; As I continued to look at the log data, I realized that every time the application hung, the ThreadAbortException&amp;#39;s stack trace had a particular third party library&amp;#39;s method at the top of the stack. The conclusion was that the application hanged whenever the thread was aborted when executing the third party library&amp;#39;s code.&lt;/p&gt;
&lt;p&gt;Reflector and half an hour later, the reason for hanging became clear. The third party code looked like this :-&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;DoX()&lt;br /&gt;{&lt;br /&gt;    Monitor.Enter(lockObj);&lt;br /&gt;    &lt;span style="color:green;"&gt;//Do some interesting stuff&lt;br /&gt;    &lt;/span&gt;Monitor.Exit(lockObj);&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Now do you see why?&amp;nbsp; If the ThreadAbortException gets thrown after acquiring the lock but before releasing it, the lock gets orphaned and no other thread will be able to acquire it. Ever. The third party library is used heavily by our app, so any thread that calls DoX after the abort will hang forever.&lt;/p&gt;
&lt;p&gt;OK, so let&amp;#39;s set it right then.&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;DoX()&lt;br /&gt;{&lt;br /&gt;    &lt;span style="color:blue;"&gt;lock&lt;/span&gt;(lockObj)&lt;br /&gt;    {&lt;br /&gt;        &lt;span style="color:green;"&gt;//Do some interesting stuff&lt;br /&gt;&lt;/span&gt;    }&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The compiler will emit a try/finally block and will call Monitor.Exit from the finally block. That should solve the problem, right?&lt;/p&gt;
&lt;p&gt;Maybe.&lt;/p&gt;
&lt;p&gt;The CLR guarantees that it won&amp;#39;t throw ThreadAbortExceptions when running finally blocks (and &lt;a href="http://msdn.microsoft.com/en-us/library/ms228973.aspx"&gt;CERs&lt;/a&gt; and constructors), so once the finally block starts executing, we&amp;#39;re safe. But what about if there is (JIT compiler generated) code that is run after the try block but before the finally block?&lt;/p&gt;
&lt;p&gt;Even assuming there is no such code, things can still fail.&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;DoY()&lt;br /&gt;{&lt;br /&gt;    &lt;span style="color:blue;"&gt;using &lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;StreamReader &lt;/span&gt;sr = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;StreamReader&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Test.txt&amp;quot;&lt;/span&gt;))&lt;br /&gt;    {}&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;If a ThreadAbortException is thrown after the StreamReader constructor runs, but before the constructed instance gets assigned to the local variable (sr), then sr won&amp;#39;t be disposed. &lt;/p&gt;
&lt;p&gt;The bottom line is that it is really hard to write code that works properly in the face of ThreadAbortExceptions. And even if you somehow manage to write it, you can never be sure that all your external libraries are written to cope with it.&lt;/p&gt;
&lt;p&gt;Moral of the story : Listen to all the good advice and don&amp;#39;t call Thread.Abort from another thread :)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1657017" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category></item><item><title>Not all IEnumerable&lt;T&gt; are equal</title><link>http://msmvps.com/blogs/senthil/archive/2008/09/04/not-all-ienumerable-lt-t-gt-are-equal.aspx</link><pubDate>Thu, 04 Sep 2008 19:25:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1646798</guid><dc:creator>Senthil</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1646798</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1646798</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2008/09/04/not-all-ienumerable-lt-t-gt-are-equal.aspx#comments</comments><description>&lt;p&gt;Implementing IEnumerable&amp;lt;T&amp;gt; can turn out to be tricky in certain cases. Consider the following code snippet&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;namespace &lt;/span&gt;Test&lt;br /&gt;{&lt;br /&gt;    &lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Program&lt;br /&gt;    &lt;/span&gt;{&lt;br /&gt;        &lt;span style="color:blue;"&gt;static void &lt;/span&gt;Main(&lt;span style="color:blue;"&gt;string&lt;/span&gt;[] args)&lt;br /&gt;        {&lt;br /&gt;            Consume(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt;() { &lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;c&amp;quot; &lt;/span&gt;});&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        &lt;span style="color:blue;"&gt;static void &lt;/span&gt;Consume&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; stream)&lt;br /&gt;        {&lt;br /&gt;            T t1 = stream.First();&lt;br /&gt;            T t2 = stream.First();&lt;br /&gt;&lt;br /&gt;            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(t1.Equals(t2));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;As you&amp;#39;d expect, it prints true. Each First() call results in a call to stream.GetEnumerator(), and each such enumerator returns elements from the beginning of the list, so calling First() twice returns the same (first) element. All good so far.&lt;/p&gt;
&lt;p&gt;Here&amp;#39;s a tiny class.&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;        class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;StringGenerator&lt;br /&gt;        &lt;/span&gt;{&lt;br /&gt;            &lt;span style="color:blue;"&gt;int &lt;/span&gt;index;&lt;br /&gt;&lt;br /&gt;            &lt;span style="color:blue;"&gt;public string &lt;/span&gt;GetNext()&lt;br /&gt;            {&lt;br /&gt;                &lt;span style="color:blue;"&gt;return &lt;/span&gt;(index++).ToString();&lt;br /&gt;            }&lt;br /&gt;        }&lt;/pre&gt;
&lt;p&gt;As you can see, it generates whole numbers as strings. Not very convenient to use though, wouldn&amp;#39;t it be great if we can wrap it and make it enumerable?&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;        static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;&amp;gt; ConvertToEnumerable(&lt;span style="color:#2b91af;"&gt;StringGenerator &lt;/span&gt;g)&lt;br /&gt;        {&lt;br /&gt;            &lt;span style="color:blue;"&gt;string &lt;/span&gt;item = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;&lt;br /&gt;&lt;br /&gt;            &lt;span style="color:blue;"&gt;while &lt;/span&gt;((item = g.GetNext()) != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)&lt;br /&gt;                &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;item;&lt;br /&gt;        }&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;ConvertToEnumerable simply loops over the list of items generated and makes use of yield return to make it enumerable.&lt;/p&gt;
&lt;p&gt;Great, now what does &lt;/p&gt;
&lt;pre class="code"&gt;        Consume(ConvertToEnumerable(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;StringGenerator&lt;/span&gt;()));&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;print?&lt;/p&gt;
&lt;p&gt;It prints false. &lt;/p&gt;
&lt;p&gt;False? FALSE? Can you figure out the reason?&lt;/p&gt;
&lt;p&gt;If you&amp;#39;ve read &lt;a href="http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx"&gt;Raymond&amp;#39;s&lt;/a&gt; posts on implementation of iterators, you should have figured it out by now. The crux of the problem is that all enumerators returned share the same instance of StringGenerator.&amp;nbsp; Calling First() twice results in two calls to GetNext() on the same StringGenerator instance, and the values returned will obviously be different. To verify that, try creating the StringGenerator instance inside the ConvertToEnumerable function - it will print true now.&lt;/p&gt;
&lt;p&gt;This bit me when I wrote code that parsed stuff out of an IEnumerable&amp;lt;string&amp;gt; instance. The actual program read text from a file, so I had a ConvertToEnumerable routine just like the one above, except that it took TextReader as the parameter. The Consume method passed the constructed IEnumerable&amp;lt;T&amp;gt; instance to various methods (say Method1 and Method2), with the assumption that whatever Method1 read off the stream won&amp;#39;t be read again by Method2. &lt;/p&gt;
&lt;p&gt;As we saw just now, this works if Consume is passed an IEnumerable&amp;lt;T&amp;gt; constructed like the StringGenerator case. It fails badly if a List&amp;lt;string&amp;gt; is passed instead. Because I wanted the &amp;quot;read elements off the stream&amp;quot; behavior, I called GetEnumerator() once for the passed IEnumerable&amp;lt;T&amp;gt; and then changed the methods called by Consume to take that IEnumerator&amp;lt;T&amp;gt; instead of IEnumerable&amp;lt;T&amp;gt;. That made the code work correctly for both cases.&lt;/p&gt;
&lt;p&gt;Moral : Make sure you understand the implications when yield returning items off a shared item source.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1646798" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category></item><item><title>String.Empty versus "" - The real deal</title><link>http://msmvps.com/blogs/senthil/archive/2008/06/27/string-empty-versus-quot-quot.aspx</link><pubDate>Fri, 27 Jun 2008 13:36:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1638404</guid><dc:creator>Senthil</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1638404</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1638404</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2008/06/27/string-empty-versus-quot-quot.aspx#comments</comments><description>&lt;p&gt;This is one topic that keeps popping up every now and then. A lot of people seem to be curious about the performance implications of using one versus the other, and not unexpectedly, a lot of different answers come up.&lt;br /&gt;&lt;/p&gt;&lt;p&gt;To settle it once for all, here&amp;#39;s a small program that uses both of them. &lt;br /&gt;&lt;/p&gt;
&lt;pre&gt;namespace ConsoleApplication&lt;br /&gt;{  &lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main()&lt;br /&gt;        {&lt;br /&gt;            Method1();&lt;br /&gt;            Method2();&lt;br /&gt;            Console.ReadLine();&lt;br /&gt;            Method1();&lt;br /&gt;            Method2();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [MethodImpl(MethodImplOptions.NoInlining)]&lt;br /&gt;        static void Method1()&lt;br /&gt;        {&lt;br /&gt;            string s = &amp;quot;&amp;quot;;&lt;br /&gt;            DoNothing(s); &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [MethodImpl(MethodImplOptions.NoInlining)]&lt;br /&gt;        static void Method2()&lt;br /&gt;        {&lt;br /&gt;            string s = string.Empty;&lt;br /&gt;            DoNothing(s);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [MethodImpl(MethodImplOptions.NoInlining)]&lt;br /&gt;        static void DoNothing(string s)&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(s);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;As you can see above, Method1 and Method2 call DoNothing, passing &amp;quot;&amp;quot; and string.Empty respectively. Now how do we compare these two? Easy, just look at the jitted code - after all, that&amp;#39;s what is going to run on the machine.&lt;/p&gt;&lt;p&gt;We&amp;#39;ll use Windbg to disassemble the code after the JITter did its job. And if you&amp;#39;re wondering why Method1 and Method2 have been called twice, now you know why - the second time around, we can look at the JITted code that was generated as part of the first time execution of each of those methods. &lt;/p&gt;&lt;p&gt;So breaking into the debugger at Console.ReadLine() and dumping the method descriptors for Program &lt;br /&gt;&lt;/p&gt;
&lt;pre&gt;0:003&amp;gt; !Name2EE Sample.exe!ConsoleApplication.Program&lt;br /&gt;...&lt;br /&gt;MethodTable: 002a3048&lt;br /&gt;&lt;br /&gt;0:003&amp;gt; !DumpMT -MD 002a3048&lt;br /&gt;...&lt;br /&gt;--------------------------------------&lt;br /&gt;   Entry MethodDesc      JIT Name&lt;br /&gt;...&lt;br /&gt;00860070   002a3020      JIT ConsoleApplication.Program.Main()&lt;br /&gt;008600a8   002a3028      JIT ConsoleApplication.Program.Method1()&lt;br /&gt;00860100   002a3030      JIT ConsoleApplication.Program.Method2()&lt;br /&gt;008600c8   002a3038      JIT ConsoleApplication.Program.DoNothing(System.String)&lt;br /&gt;002ac021   002a3040     NONE ConsoleApplication.Program..ctor()&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;shows the method descriptors for all the methods in that class. Now, using !u to disassemble code for Method1&lt;/p&gt;
&lt;pre&gt;0:003&amp;gt; !u 002a3028&lt;br /&gt;Normal JIT generated code&lt;br /&gt;ConsoleApplication.Program.Method1()&lt;br /&gt;Begin 008600a8, size d&lt;br /&gt;008600a8 8b0d3c30e402    mov     ecx,dword ptr ds:[2E4303Ch] (&amp;quot;&amp;quot;)&lt;br /&gt;008600ae ff158c302a00    call    dword ptr ds:[2A308Ch] (ConsoleApplication.Program.DoNothing(System.String), mdToken: 06000004)&lt;br /&gt;008600b4 c3              ret&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt; and then for Method2&lt;/p&gt;
&lt;pre&gt;0:003&amp;gt; !u 002a3030&lt;br /&gt;Normal JIT generated code&lt;br /&gt;ConsoleApplication.Program.Method2()&lt;br /&gt;Begin 00860100, size c&lt;br /&gt;00860100 8b0d2c10e402    mov     ecx,dword ptr ds:[2E4102Ch] (&amp;quot;&amp;quot;)&lt;br /&gt;00860106 e8bdffffff      call    008600c8 (ConsoleApplication.Program.DoNothing(System.String), mdToken: 06000004)&lt;br /&gt;0086010b c3              ret&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;shows that, surprise surprise,&lt;b&gt; the generated assembly code is identical&lt;/b&gt;.&lt;b&gt; &lt;/b&gt;The only difference is the address referenced in the mov instruction.&lt;/p&gt;&lt;p&gt;So there you have it - the JITter generates the same code whether you use String.Empty or &amp;quot;&amp;quot;, and there should no difference in performance.&lt;/p&gt;&lt;p&gt;PS : It&amp;#39;s interesting to note that the two addresses are different, even though the string contents are the same. Address 2E4303Ch in the disassembly for Method1 is the address referring to an interned string object with the content &amp;quot;&amp;quot;. You can verify that by creating another string variable initialized to &amp;quot;&amp;quot; and disassembling that code - the same address (2E4303Ch) will be referenced there as well. What&amp;#39;s surprising is that the address referenced in Method2 is different - which means the string object referenced by string.Empty is not the interned object. Wonder why - maybe because it&amp;#39;s ngen&amp;#39;ned code? &lt;/p&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1638404" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx">software</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+debugging+Windbg+leaks/default.aspx">software debugging Windbg leaks</category></item><item><title>Itertools for C# - Tee</title><link>http://msmvps.com/blogs/senthil/archive/2008/05/05/itertools-for-c-tee.aspx</link><pubDate>Mon, 05 May 2008 17:03:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1614250</guid><dc:creator>Senthil</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1614250</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1614250</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2008/05/05/itertools-for-c-tee.aspx#comments</comments><description>&lt;p&gt;Tee is a cool function that &amp;quot;clones&amp;quot; enumerators whatever their current state is - it basically allows you to branch off an enumerator into as many enumerators as you want, all independent of each other.&lt;/p&gt;&lt;p&gt;&amp;nbsp;You can do something like&lt;/p&gt;
&lt;pre&gt;List&amp;lt;int&amp;gt; list = new List&amp;lt;int&amp;gt; { 1, 2, 3, 4, 5 };&lt;br /&gt;&lt;br /&gt;IEnumerator&amp;lt;int&amp;gt; iterable1 = list.GetEnumerator();&lt;br /&gt;&lt;br /&gt;IEnumerator&amp;lt;int&amp;gt; []teedIterables = Itertools.Tee(iterable1, 2);&lt;br /&gt;&lt;br /&gt;foreach(int val in teedIterables[0])&lt;br /&gt;{&lt;br /&gt;   Console.WriteLine(val);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;foreach(int val in teedIterables[1])&lt;br /&gt;{&lt;br /&gt;   Console.WriteLine(val);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// prints 1 2 3 4 5 1 2 3 4 5&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;
If there was a iterable1.MoveNext() before the call to Tee, then the output would have been 2 3 4 5 2 3 4 5.

The implementation proved to be pretty interesting - and complicated, partly because the C# compiler does not allow the yield statement inside anonymous methods. Here&amp;#39;s the implementation.
&lt;/p&gt;
&lt;pre&gt;public static IEnumerator&amp;lt;T&amp;gt;[] Tee&amp;lt;T&amp;gt;(IEnumerator&amp;lt;T&amp;gt; source, int count)&lt;br /&gt;{&lt;br /&gt;    List&amp;lt;T&amp;gt; tValues = new List&amp;lt;T&amp;gt;();&lt;br /&gt;    IEnumerator&amp;lt;T&amp;gt;[] results = new IEnumerator&amp;lt;T&amp;gt;[count];&lt;br /&gt;&lt;br /&gt;    for (int i = 0; i &amp;lt; count; ++i)&lt;br /&gt;    {&lt;br /&gt;       int currentLocation = 0;&lt;br /&gt;       results [ i ] = CreateEnumerator(source, new EnumeratorState&amp;lt;T&amp;gt;() { CurrentLocation = currentLocation, TValues = tValues });&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return results;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private static IEnumerator&amp;lt;T&amp;gt; CreateEnumerator&amp;lt;T&amp;gt;(IEnumerator&amp;lt;T&amp;gt; source, EnumeratorState&amp;lt;T&amp;gt; state)&lt;br /&gt;{&lt;br /&gt;   while (true)&lt;br /&gt;   {&lt;br /&gt;      if (state.CurrentLocation &amp;lt; state.TValues.Count)&lt;br /&gt;      {&lt;br /&gt;          yield return state.TValues[state.CurrentLocation++];&lt;br /&gt;      }&lt;br /&gt;      else&lt;br /&gt;      {&lt;br /&gt;         if (source.MoveNext())&lt;br /&gt;         {&lt;br /&gt;            state.TValues.Add(source.Current);&lt;br /&gt;            state.CurrentLocation = state.TValues.Count;&lt;br /&gt;            yield return source.Current;&lt;br /&gt;         }&lt;br /&gt;         else&lt;br /&gt;         {&lt;br /&gt;             break;&lt;br /&gt;         }&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class EnumeratorState&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;   internal int CurrentLocation { get; set; }&lt;br /&gt;   internal List&amp;lt;T&amp;gt; TValues { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt;There&amp;#39;s a fair bit of code involved, as you can see. The basic idea behind the implementation is to maintain a list as a backing store. Each teed off enumerator attempts to read from the list - if it hits the end of the list, it advances the original enumerator&amp;nbsp; and gets the current value, updates the list and returns that value. The rest of the code is plumbing to work around the inability to use yield inside an anonymous method. The code basically does what the compiler would have done - there&amp;#39;s the EnumeratorState class to hold captured variables and a new instance of the class is created and passed to CreateEnumerator, which is in the place of the anonymous method.&lt;/p&gt;&lt;p&gt;Tee is that kind of function that is incredibly useful once you know you can do such a thing. Let&amp;#39;s say you have an application that needs to process lines in a file, but the processing can happen in different contexts, independent of each other. Take for example, a log parser, that goes through each line in a file, looking for the start of an operation. The log parser notifies another component once it finds the start of the operation and proceeds through the file looking for the next operation. Normally, you&amp;#39;ll solve the problem by adding the component to a list that gets notified after the parser reads each line. With Tee, you can simply tee off an enumerator and pass it to the other component - both the log parser and the component now have independent enumerators and can actually run in parallel. And you can tee off as many enumerators as there are components. &lt;/p&gt;&lt;p&gt;With that, we come to the end of this series of blog posts on implementing itertools in C#. The source code for all the functions implemented in the series is available at &lt;a href="http://code.msdn.microsoft.com/itertools"&gt;http://code.msdn.microsoft.com/itertools&lt;/a&gt;.&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1614250" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx">software</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category></item><item><title>Not just a function : Generating functions</title><link>http://msmvps.com/blogs/senthil/archive/2008/02/12/more-than-just-functions-generating-functions.aspx</link><pubDate>Tue, 12 Feb 2008 15:29:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1510302</guid><dc:creator>Senthil</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1510302</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1510302</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2008/02/12/more-than-just-functions-generating-functions.aspx#comments</comments><description>&lt;p&gt;Every now and then, you hit some problem that a programming language helps solve very cleanly. Here&amp;#39;s the problem.&lt;br /&gt;&lt;/p&gt;&lt;p&gt;You are writing a series of functions that return a bool depending on some condition (predicates). Something like&lt;br /&gt;&lt;/p&gt;&lt;pre&gt;bool Foo(State t);&lt;/pre&gt;&lt;p&gt;Let&amp;#39;s also assume that State is defined as&lt;/p&gt;&lt;pre&gt;class State&amp;nbsp; { Color c; ... }&lt;/pre&gt;&lt;p&gt;You have a set of colors, known at compile time, for which Foo should return true. How would you go about doing it?&lt;/p&gt;&lt;p&gt;You could pack the set of colors into an array and write Foo so that at runtime, it searches the color array and returns true if the color passed is in the array. Something like&lt;/p&gt;&lt;pre&gt;bool Foo(State t) { return colors.IndexOf(t.Color) != -1; }&lt;/pre&gt;&lt;p&gt;Assume that, for design reasons, it isn&amp;#39;t really possible to allow access to colors from within Foo. Then what?&lt;/p&gt;&lt;p&gt;Anonymous methods and closures, of course. How about writing a function, that returns a Foo that returns true only if the color matches. Whew, that sounds confusing, but the code looks pretty simple. &lt;/p&gt;&lt;pre&gt;Foo GenerateFoo(Color color) { return delegate(Color passedColor) { return color == passedColor; } }&lt;/pre&gt;&lt;p&gt;You can then call GenerateFoo(Color.Red) to get a Foo that will return true only if it is called with Color.Red, call GenerateFoo(Color.Orange) to get one that returns true only if called with Color.Orange and so on.&lt;/p&gt;&lt;pre&gt;Foo redFoo = GenerateFoo(Color.Red);
Foo orangeFoo = GenerateFoo(Color.Orange);
Console.WriteLine(redFoo(Color.Red)); // prints true
Console.WriteLine(redFoo(Color.Yellow)); // prints false&lt;/pre&gt;&lt;p&gt;Nifty, eh? &lt;br /&gt;&lt;/p&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1510302" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category></item><item><title>C# 3.0 compiler bug - Using object initializers, generics and value types</title><link>http://msmvps.com/blogs/senthil/archive/2007/12/26/c-3-0-compiler-bug-using-object-initializers-generics-and-value-types.aspx</link><pubDate>Wed, 26 Dec 2007 17:44:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1420645</guid><dc:creator>Senthil</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1420645</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1420645</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2007/12/26/c-3-0-compiler-bug-using-object-initializers-generics-and-value-types.aspx#comments</comments><description>&lt;p&gt;There is a description of the bug &lt;a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=319430"&gt;here&lt;/a&gt;. The following piece of code demonstrates the bug.&lt;/p&gt;
&lt;pre&gt;    class Program
    {
        interface I
        {
            int X { get; set; }
        }

        struct S : I
        {
            public int X { get; set; }
        }

        static void Main(string[] args)
        {
            Func&amp;lt;S&amp;gt;();
        }

        static void Func&amp;lt;T&amp;gt;() where T : I, new()
        {
            var c = new T() { X = 1 };
            Console.WriteLine(c.X);
        }
    }
&lt;/pre&gt;&lt;p&gt;The code prints 0 instead of 1. The bug goes away if object initializers are not used - changing var c = new T() { X = 1 }; to var c = new T(); c.X = 1; will print 1.&lt;/p&gt;&lt;p&gt;I had assumed all along that object initializers were transformed into property setters at the source code level (or somewhere above IL). This bug doesn&amp;#39;t help much to confirm that :)&lt;/p&gt;&lt;p&gt;Anyway, let&amp;#39;s see what&amp;#39;s causing the problem. Peeking into the generated IL,&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;   .locals init (
        [0] !!T c,
        [1] !!T &amp;lt;&amp;gt;g__initLocal0,
        [2] !!T CS$0$0000)
        ... // Store zeroed out instance of S in locals[1]
    L_0022: ldloc.1 
    L_0023: box !!T
    L_0028: ldc.i4.1 
    L_0029: callvirt instance void CSharp3Test.Program/I::set_X(int32)
    L_002e: nop 
    L_002f: ldloc.1 
    L_0030: stloc.0 
    L_0031: ldloca.s c
    L_0033: constrained !!T
    L_0039: callvirt instance int32 CSharp3Test.Program/I::get_X()
    L_003e: call void [mscorlib]System.Console::WriteLine(int32)
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;Can you spot the problem now?&lt;/p&gt;&lt;p&gt;You can see that at L_0023, S is boxed and the boxed instance is used to make the virtual call to set X. You can also see that the boxed instance is not stored in any of the local variables, the &lt;b&gt;callvirt&lt;/b&gt; instruction pops it off the stack and then it&amp;#39;s gone. To load the value of X, the &lt;b&gt;callvirt&lt;/b&gt; instruction is given a reference to c (locals[0]), which contains the unboxed instance of the struct. Which is why we are getting a 0 (the default value), instead of 1. Essentially, the compiler is generating the equivalent IL for something like&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;   S s = new S();
   I i = s;
   i.X = 10;
   Console.WriteLine(s.X);
&lt;/pre&gt;&lt;p&gt;This again prints 0 instead of 10, because i is assigned a different (boxed) instance of S and therefore changing i.X doesn&amp;#39;t change s.X.&lt;br /&gt;&lt;/p&gt;But then how does doing the initialization in two steps (var c = new T(); c.X = 1) work. The answer - Two step initialization does not use boxing when setting the value of X. Here&amp;#39;s how the generated IL looks.&lt;br /&gt;
&lt;pre&gt;   .locals init (
        [0] !!T c,
        [1] !!T CS$0$0000)
    L_0021: stloc.0 
    L_0022: ldloca.s c
    L_0024: ldc.i4.1 
    L_0025: constrained !!T
    L_002b: callvirt instance void CSharp3Test.Program/I::set_X(int32)
    L_0030: nop 
    L_0031: ldloca.s c
    L_0033: constrained !!T
    L_0039: callvirt instance int32 CSharp3Test.Program/I::get_X()
    L_003e: call void [mscorlib]System.Console::WriteLine(int32)
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt;The box instruction is gone, instead, the compiler has generated a constrained prefix for the &lt;b&gt;callvirt&lt;/b&gt; instruction. MSDN says that&lt;/p&gt;&lt;p&gt;&amp;quot;When a &lt;span class="keyword"&gt;callvirt&lt;/span&gt; &lt;span class="parameter"&gt;method&lt;/span&gt; instruction has been prefixed by &lt;span class="keyword"&gt;constrained&lt;/span&gt; &amp;nbsp;&lt;span class="parameter"&gt;thisType&lt;/span&gt;, the instruction is executed as follows: &lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;If &lt;span class="parameter"&gt;thisType&lt;/span&gt; is a reference type (as opposed to a value type) then &lt;span class="parameter"&gt;ptr&lt;/span&gt; is dereferenced and passed as the &amp;#39;this&amp;#39; pointer to the &lt;span class="keyword"&gt;callvirt&lt;/span&gt; of &lt;span class="parameter"&gt;method&lt;/span&gt;.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;If &lt;span class="parameter"&gt;thisType&lt;/span&gt; is a value type and &lt;span class="parameter"&gt;thisType&lt;/span&gt; implements &lt;span class="parameter"&gt;method&lt;/span&gt; then &lt;span class="parameter"&gt;ptr&lt;/span&gt; is passed unmodified as the &amp;#39;this&amp;#39; pointer to a &lt;span class="keyword"&gt;call&lt;/span&gt; &amp;nbsp;&lt;span class="parameter"&gt;method&lt;/span&gt; instruction, for the implementation of &lt;span class="parameter"&gt;method&lt;/span&gt; by &lt;span class="parameter"&gt;thisType&lt;/span&gt;.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;...&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&amp;nbsp;&amp;quot;&lt;/p&gt;&lt;p&gt;In other words, the address of the instance is passed as the this parameter to the &lt;b&gt;call &lt;/b&gt;method - no boxing at all. If you&amp;#39;d looked carefully enough, the getter for X uses the constrained prefix, even in our buggy IL (the first listing). &lt;br /&gt;&lt;/p&gt;&lt;p&gt;That explains the bug then, but opens up another question. If virtual dispatch can be done for a value type without boxing, then why not do it that way for&lt;/p&gt;&lt;pre&gt;   S s = new S();&lt;br /&gt;   I i = s;&lt;br /&gt;   i.X = 10;&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;&amp;nbsp;as well? Mind you, virtual dispatch doesn&amp;#39;t mean anything for value types, as they cannot derive from or derived by anything else, so any &lt;b&gt;callvirt&lt;/b&gt; instruction on value types can be treated as a straight &lt;b&gt;call&lt;/b&gt; instruction. The constrained prefix does exactly this, after making sure that &lt;b&gt;this &lt;/b&gt;is a value type. So why not use it for all virtual calls? Performance (not many value types implementing interfaces)? &lt;/p&gt;&lt;p&gt;What do you think?&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1420645" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category></item><item><title>Mucking around with instance field initializers - Part 2</title><link>http://msmvps.com/blogs/senthil/archive/2007/12/23/mucking-around-with-instance-field-initializers-part-2.aspx</link><pubDate>Sun, 23 Dec 2007 18:20:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1414545</guid><dc:creator>Senthil</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1414545</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1414545</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2007/12/23/mucking-around-with-instance-field-initializers-part-2.aspx#comments</comments><description>&lt;p&gt;We saw in &lt;a href="http://msmvps.com/blogs/senthil/archive/2007/12/06/mucking-around-with-instance-field-initializers-part-1.aspx" target="_blank"&gt;Part 1&lt;/a&gt; that C# doesn&amp;#39;t allow an instance field initializer to refer another field in the class. Before trying to figure out why, let&amp;#39;s first see if this is a restriction imposed by C#, rather than by the CLR.&amp;nbsp;&lt;/p&gt;&lt;p&gt;Some disassembling and reassembling later, this is what the new IL code looks like.&lt;br /&gt;
&lt;/p&gt;&lt;pre&gt;    IL_0000:  ldarg.0&lt;br /&gt;    IL_0001:  ldc.i4.1&lt;br /&gt;    IL_0002:  stfld      int32 ConsoleApplication1.Program::x&lt;br /&gt;    IL_0007:  ldarg.0&lt;br /&gt;    IL_0008:  ldarg.0&lt;br /&gt;    IL_000b:  ldfld      int32 ConsoleApplication1.Program::x&lt;br /&gt;    IL_0009:  ldc.i4.1&lt;br /&gt;    IL_000a:  add&lt;br /&gt;    IL_000c:  stfld      int32 ConsoleApplication1.Program::y&lt;br /&gt;    IL_000d:  ldarg.0&lt;br /&gt;    IL_000e:  ldfld      int32 ConsoleApplication1.Program::y&lt;br /&gt;    IL_000f:  call       void [mscorlib]System.Console::WriteLine(int32)&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;&amp;nbsp;It&amp;#39;s basically the same code in Part 1, except for the initialization of y. Instead of initializing y to 2, the code tries to load this.x, add 1 to it, store the result in y (y = x + 1) and then print out the result. The call to the constructor of System.Object comes next, but I&amp;#39;ve left that out for clarity.&amp;nbsp; &lt;/p&gt;&lt;p&gt;Guess what, it works! The code assembles, checks out with peverify and runs fine, printing the value 2. &lt;/p&gt;&lt;p&gt;So, it looks like the CLR does not have any problems accessing other instance fields when initializing them. Then why doesn&amp;#39;t the C# compiler like them?&lt;/p&gt;&lt;p&gt;How about fields inherited from a base class? If C# doesn&amp;#39;t have the instance field initializer restriction, then the following piece of code should compile . What do you expect the value of y to be?&lt;/p&gt;&lt;pre&gt;    class A&lt;br /&gt;    {&lt;br /&gt;        protected int x = 1;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class B : A&lt;br /&gt;    {&lt;br /&gt;        int y = x + 1;&lt;br /&gt;        B() { Console.WriteLine(y); }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;&amp;nbsp;1? 2? It depends on where the C# compiler puts the instance field initialization code. According to the current spec, it&amp;#39;s placed before the call to the base class constructor, which means that y will be initialized to 1. Suddenly, the derived class now gets to access uninitialized base class state. Not good at all. &lt;/p&gt;&lt;p&gt;You could argue that the compiler knows about inherited fields and therefore can apply the restriction only to those fields - but that would add a nasty special case to the &amp;quot;you-cannot-reference-during-instance-field-initialization&amp;quot; list. I don&amp;#39;t think it will be intuitive either - a typical programmer will be surprised if a &amp;quot;Move to base class&amp;quot; refactor suddenly breaks working code.&lt;/p&gt;&lt;p&gt;Static fields don&amp;#39;t have this problem - they aren&amp;#39;t really &amp;quot;inherited&amp;quot;. Which could be why the compiler allows static field initializers to reference other fields.&lt;/p&gt;&lt;p&gt;What do you think?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1414545" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category></item><item><title>Mucking around with instance field initializers - Part 1</title><link>http://msmvps.com/blogs/senthil/archive/2007/12/06/mucking-around-with-instance-field-initializers-part-1.aspx</link><pubDate>Thu, 06 Dec 2007 13:02:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1382869</guid><dc:creator>Senthil</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1382869</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1382869</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2007/12/06/mucking-around-with-instance-field-initializers-part-1.aspx#comments</comments><description>&lt;p&gt;What do you think of the following piece of code?&lt;/p&gt;
&lt;pre&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        int x = 1;&lt;br /&gt;        int y = x + 1;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;Looks simple, except that it doesn&amp;#39;t compile (error CS0236: A field initializer cannot reference the non-static field, method, or property &amp;#39;Program.x&amp;#39;)&lt;br /&gt;&lt;br /&gt;Try making x and y static - the code will compile fine now. I have been trying to find out why - so far, I haven&amp;#39;t got a clue. Just in case it&amp;#39;s not obvious, I do know that moving y = x + 1 into the body of Program&amp;#39;s constructor will get me what I want, but I was (and am) curious to know why field initializers, and only instance field initializers, aren&amp;#39;t allowed to access non-static fields. &lt;/p&gt;&lt;p&gt;The C# spec says that &lt;span class="paragraph"&gt;&lt;span class="sentence"&gt;field initializers &amp;quot;correspond to a sequence of assignments that are executed immediately upon entry to any one of the instance constructors&amp;quot;&lt;/span&gt;&lt;/span&gt;, just before the call to the base class constructor. When I generated IL for Program&amp;#39;s constructor after replacing y = x + 1 with y = 2, it looked like this&lt;br /&gt;&lt;/p&gt;
&lt;pre&gt;    L_0000: ldarg.0 &lt;br /&gt;    L_0001: ldc.i4.1 &lt;br /&gt;    L_0002: stfld int32 ConsoleApplication1.Program::x&lt;br /&gt;    L_0007: ldarg.0 &lt;br /&gt;    L_0008: ldc.i4.2 &lt;br /&gt;    L_0009: stfld int32 ConsoleApplication1.Program::y&lt;br /&gt;    L_000e: ldarg.0 &lt;br /&gt;    L_000f: call instance void [mscorlib]System.Object::.ctor()&lt;br /&gt;    L_0014: nop &lt;br /&gt;    L_0015: ret &lt;br /&gt;&lt;/pre&gt;&lt;p&gt;
The generated IL matches with the spec - 1 and 2 are stfld&amp;#39;ed into x and y before calling the base class constructor (System.Object::.ctor()).&lt;/p&gt;&lt;p&gt;The C# spec also says that a field initializer is not allowed to reference the &lt;b&gt;this&lt;/b&gt; pointer - &amp;quot;&lt;span class="paragraph"&gt;&lt;span class="sentence"&gt; variable initializer for an instance field cannot reference the instance being created.&amp;quot; It doesn&amp;#39;t say why though.&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;&lt;p&gt;The IL shown above clearly indicates that &lt;b&gt;this&lt;/b&gt; (ldarg.0) is valid when storing 1 and 2 into x and y. So why doesn&amp;#39;t C# allow y = x + 1?&lt;/p&gt;&lt;p&gt;I initially wondered if that rule is to prevent code like this&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        int x = y + 1;&lt;br /&gt;        int y = x + 1;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;but then, the C# spec clearly says that the variable initializers will be run in &amp;quot;textual&amp;quot; order. If you combine that with the fact that x and y will be assigned their default values even before their variable initializers run, you&amp;#39;ll see that the above code should run fine, resulting in x = 1 (because y is zero) and y = 2. You can make x and y static and run the code, you will see the same result. &lt;/p&gt;&lt;p&gt;So again, why? Can you figure out why? We&amp;#39;ll do some more digging into this in the next post.&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1382869" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx">software</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category></item><item><title>Type inference != Dynamic typing</title><link>http://msmvps.com/blogs/senthil/archive/2007/11/19/type-inference-dynamic-typing.aspx</link><pubDate>Mon, 19 Nov 2007 16:27:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1335878</guid><dc:creator>Senthil</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1335878</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1335878</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2007/11/19/type-inference-dynamic-typing.aspx#comments</comments><description>&lt;p&gt;Local variable type inferencing is a new feature in C# 3.5 - a very &amp;quot;handy&amp;quot; one, in that it saves a lot of typing. Basically, it lets you do&amp;nbsp;&lt;/p&gt;&lt;pre&gt;var dict = new Dictionary&amp;lt;string, List&amp;lt;int, Dictionary&amp;lt;int, string&amp;gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;p&gt;instead of&amp;nbsp;&lt;/p&gt;&lt;pre&gt;Dictionary&amp;lt;string, List&amp;lt;int, Dictionary&amp;lt;int, string&amp;gt;&amp;gt;&amp;gt; dict = Dictionary&amp;lt;string, List&amp;lt;int, Dictionary&amp;lt;int, string&amp;gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;p&gt;That&amp;#39;s pretty cool, but remember, C# is still a statically typed language. dict is statically bound to the type Dictionary&amp;lt;string, List&amp;lt;int, Dictionary&amp;lt;int, string&amp;gt;&amp;gt;&amp;gt; and you cannot change it. You cannot do&lt;/p&gt;&lt;pre&gt;dict = Dictionary&amp;lt;int, string&amp;gt;();&lt;/pre&gt;&lt;p&gt;in the same method. The compiler will complain that the type on the RHS is not convertible to the statically bound type of dict. &lt;/p&gt;&lt;p&gt;Contrast this to a dynamically typed language like Javascript, which also uses the var keyword to declare variables.&amp;nbsp;&lt;/p&gt;&lt;pre&gt;var x = 1;&lt;p&gt;x = new Array();&lt;/p&gt;&lt;p&gt;x = &amp;quot;23&amp;quot;;&lt;/p&gt;&lt;/pre&gt;&lt;p&gt;Or to Python&amp;nbsp;&lt;/p&gt;&lt;pre&gt;x = 42&lt;p&gt;x = def fn(z) : return z + 1&lt;/p&gt;&lt;/pre&gt;&lt;p&gt;In such languages, variables (x, in our example) simply act as placeholders and get bound to the type of the value they are holding at the moment. In the first example, x is holding an integer after executing the first line. After executing the second line, it&amp;#39;s holding an array. If the same two lines of code were to be written in a statically typed language, the second line would be correct only if an array is somehow convertible to an int.&lt;/p&gt;&lt;p&gt;The point of the post - don&amp;#39;t be misled by the var keyword. The variable it declares is still a good old statically typed variable. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1335878" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx">software</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category></item><item><title>Mixing generics and polymorphism</title><link>http://msmvps.com/blogs/senthil/archive/2007/10/14/mixing-generics-and-polymorphism.aspx</link><pubDate>Sun, 14 Oct 2007 16:29:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1247436</guid><dc:creator>Senthil</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=1247436</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=1247436</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2007/10/14/mixing-generics-and-polymorphism.aspx#comments</comments><description>&lt;p&gt;Polymorphism, which attempts to hide differences in implementation, and generics, which attemtps to highlight them by providing exact information about types, don&amp;#39;t seem to mix very well. Consider the following fairly common pattern.&lt;/p&gt;&lt;pre&gt;        class Base
        {
        }

        class Derived : Base
        {
        }

        abstract class Manipulator
        {
            List&amp;lt;Base&amp;gt; list;

            public Manipulator(List&amp;lt;Base&amp;gt; list)
            {
                this.list = list;
            }
         }

        class BaseManipulator : Manipulator
        {
            public BaseManipulator(List&amp;lt;Base&amp;gt; list)
                : base(list)
            { }
        }

        class DerivedManipulator : Manipulator
        {
            public DerivedManipulator(List&amp;lt;Derived&amp;gt; list)
                : base(list)
            { }
        }

        public static void Main()
        {
            List&amp;lt;Derived&amp;gt; list = new List&amp;lt;Derived&amp;gt;();
            list.Add(new Derived());
            DerivedManipulator d = new DerivedManipulator(list);
        }
&lt;/pre&gt;
&lt;p&gt;The code above will not compile - the compiler complains that List&amp;lt;Derived&amp;gt;&amp;nbsp;cannot be converted to List&amp;lt;Base&amp;gt; in DerivedManipulator&amp;#39;s constructor. Which seems kindof strange, given that Derived[] is implicitly convertible to Base[]. But what would happen if implicit conversion occurred with generics?&lt;/p&gt;&lt;pre&gt;List&amp;lt;Derived&amp;gt; derivedList = new List&amp;lt;Derived&amp;gt;();
List&amp;lt;Base&amp;gt; baseList = derivedList;
baseList.Add(new Base());
Derived d = derivedList[0]; // BOOM&lt;/pre&gt;
&lt;p&gt;All hell&amp;nbsp;will break loose. The type safety&amp;nbsp;that generics offer will disappear, obviating the very need for generics.&lt;/p&gt;
&lt;p&gt;What can be done then? We could make Manipulator a generic class, taking the type of the List as a generic parameter and make DerivedManipulator derive from Manipulator&amp;lt;Derived&amp;gt;. But then we are only shifting the problem - treating Manipulators polymorphically becomes impossible then. &lt;/p&gt;
&lt;p&gt;There seems to be a basic impedance mismatch between polymorphism and generics. Does anyone know of a better way to solve the problem?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1247436" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx">software</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/generics/default.aspx">generics</category><category domain="http://msmvps.com/blogs/senthil/archive/tags/polymorphism/default.aspx">polymorphism</category></item><item><title>The quirky ?:</title><link>http://msmvps.com/blogs/senthil/archive/2007/05/19/the-quirky.aspx</link><pubDate>Sat, 19 May 2007 18:03:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:913957</guid><dc:creator>Senthil</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/rsscomments.aspx?PostID=913957</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/senthil/commentapi.aspx?PostID=913957</wfw:comment><comments>http://msmvps.com/blogs/senthil/archive/2007/05/19/the-quirky.aspx#comments</comments><description>
&lt;p&gt;If there was ever a poll conducted for the most favorite C# operator, I&amp;#39;d guess the conditional operator ?:, also known as the ternary operator, will win hands down. I find it to be one of those tools that make things shorter and clearer at the same time. But how well do you know the operator?&lt;/p&gt;

&lt;p&gt;What do you think is wrong with the following piece of code?&lt;/p&gt;

&lt;pre&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; interface IDoer {}&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; class ADoer : IDoer { }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; class BDoer : IDoer { }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; class Program&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; static void Main(string[] args)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; bool flag = bool.Parse(args[0]);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IDoer doer = flag ? new ADoer() : new BDoer();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/pre&gt;
&lt;p&gt;Looks straightforward, doesn&amp;#39;t it? Yet, this does not compile; the error being&lt;/p&gt;

&lt;pre&gt;error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between &amp;#39;ADoer&amp;#39; and &amp;#39;BDoer&amp;#39;&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;a href="http://www.jaggersoft.com/csharp_standard/14.12.htm" target="_blank"&gt;C# spec&lt;/a&gt; says that the two expressions that appear on either side of the : must be one of the following
&lt;/p&gt;&lt;ul&gt;
&lt;li&gt;Both of them should be of the same type&lt;/li&gt;

&lt;li&gt;The first one should be convertible to the second&lt;/li&gt;

&lt;li&gt;The second one should be convertible to the first&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the above case, ADoer and BDoer are both convertible to IDoer (because they implement IDoer), but  because neither of them is implicitly convertible to the other, compilation fails. It doesn&amp;#39;t matter to the compiler that the result of the expression is always convertible to IDoer, all it cares about is the deduction of the type of the ternary expression.&lt;/p&gt;

&lt;p&gt;I guess this is one of those places where static typing gets in the way of the developer, instead of helping him. You win some, you lose some :)&lt;/p&gt;

&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=913957" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx">software C# language</category></item></channel></rss>