<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.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>Fabulous Adventures In Coding : Puzzles</title><link>http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx</link><description>Tags: Puzzles</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Always write a spec, part one</title><link>http://blogs.msdn.com/ericlippert/archive/2009/11/19/always-write-a-spec-part-one.aspx</link><pubDate>Thu, 19 Nov 2009 14:45:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9921545</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>27</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9921545.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9921545</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;Joel had a great series of articles many years ago about &lt;A href="http://www.joelonsoftware.com/articles/fog0000000036.html" mce_href="http://www.joelonsoftware.com/articles/fog0000000036.html"&gt;the benefits of writing functional specifications&lt;/A&gt;, that is, specifications of how the product looks to its users. I want to talk a bit about technical specifications, that is, a specification of how something actually works behind the scenes. A while back, I described how I wrote a seemingly-trivial piece of code by &lt;A href="http://blogs.msdn.com/ericlippert/archive/2009/06/01/bug-psychology.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2009/06/01/bug-psychology.aspx"&gt;first writing the technical spec, and then writing the code to exactly implement the spec&lt;/A&gt;, and the test cases to test each statement of the spec. I use this technique frequently; it almost always saves me time and effort. If you don't write a spec first, it's very easy to get bogged down in a morass of bugs, and hard to know when you're actually done writing the code.&lt;/P&gt;
&lt;P&gt;Here's an example of another seemingly-trivial function that &lt;A href="http://stackoverflow.com/questions/921180/c-round-up/926806#926806" mce_href="http://stackoverflow.com/questions/921180/c-round-up/926806#926806"&gt;smart people gave a good half-dozen completely wrong answers to because they didn't write a spec&lt;/A&gt;. Notice how once I state what the spec is, the code follows very naturally.&lt;/P&gt;
&lt;P&gt;I thought I might go through a recent example of a slightly less trivial problem. I needed a function in the compiler which could take a valid list of arguments A1 to an applicable method M, and give me back two lists. The first result list is a list of &lt;EM&gt;local variable declarations&lt;/EM&gt;, L, the second, another argument list, A2. Here's the kicker: evaluating each member of A2 &lt;EM&gt;must have no side effects&lt;/EM&gt;. And, the combination of executing L followed by M(A2) must give &lt;EM&gt;exactly the same results&lt;/EM&gt; as executing M(A1). (I also knew that the members of A1 had already had all the conversions generated to make them match the types of M's parameter list, and so on. Overload resolution was completely done at this point.)&lt;/P&gt;
&lt;P&gt;Why I needed such a function is not particularly important; perhaps you can speculate as to why I needed it.&lt;/P&gt;
&lt;P&gt;So I started writing a spec, starting with the description above: the function T takes a valid list... blah blah blah.&lt;/P&gt;
&lt;P&gt;That's not enough of a spec to actually write code. &lt;/P&gt;
&lt;P&gt;I realized that some expressions in A1 might have side effects, and some might not. If an expression had side effects, then I could declare a temp local, execute the side effects, assign the result to the local, and then use the local as the expression in the same place in A2.&lt;/P&gt;
&lt;P&gt;Super. Now I can write more sentences in my spec.&lt;/P&gt;
&lt;HR&gt;

&lt;DIV class=spec&gt;
&lt;P&gt;For each argument x in A1, we potentially generate a temporary value as follows: First, if x has no side effects, then simply keep x in the appropriate place in A2. Otherwise, if x does have side effects, then generate a temporary variable declaration in L, var temp = x. Then put an expression that evaluates the temporary variable in the appropriate place in A2.&lt;/P&gt;&lt;/DIV&gt;
&lt;HR&gt;

&lt;P&gt;Then I thought "can I correctly implement this spec?"&lt;/P&gt;
&lt;P&gt;I started thinking about the possible cases for the input, A1. The members of A1 could be passed by value, out, or ref; I already knew they were correct, since the particular method M was an applicable method of argument list A1. In this particular point in the compilation process, there was no need to worry about whether there were "params" arguments, whether there were missing arguments with default values, and so on; that had already been taken care of. I also noted that whether they were "ref" or "out" was irrelevant; ref and out are the same thing behind the scenes. As far as the compiler is concerned, the only difference between them is that the definite assignment rules are different for each.&amp;nbsp;So we had two cases for each argument: it's being passed by value, or by ref/out. &lt;/P&gt;
&lt;P&gt;If it's being passed by ref/out, then what we actually do is we pass&amp;nbsp;the managed address of&amp;nbsp;a variable to the method. In M(ref int x), the type of x is actually a special type int&amp;amp;, "managed reference to variable of type int", which is not a legal type in C#. That's why we hide it from you by requiring a goofy "ref" syntax any time you want to talk about a managed reference to a variable.&lt;/P&gt;
&lt;P&gt;Unfortunately, our IL generation pass was written with the assumption that all local variables are never of these magic managed-reference-to-variable types. I was then faced with a choice. Either come up with a technique for working with this limitation, or rewrite the most complicated code in the IL gen to support this scenario. (The code which figures out how to deal with managed references is quite complex.) I decided to opt for the former strategy. Which meant more spec work, since our spec now doesn't handle these cases!&lt;/P&gt;
&lt;HR&gt;

&lt;DIV class=spec&gt;
&lt;P&gt;For each argument x in A1, we potentially generate a temporary value as follows: &lt;/P&gt;
&lt;P&gt;First, if x has no side effects, then simply keep x in the appropriate place in A2. &lt;/P&gt;
&lt;P&gt;Otherwise, if x does have side effects &lt;STRONG&gt;and corresponds to a value parameter&lt;/STRONG&gt;, then generate ... etc.&lt;/P&gt;
&lt;P&gt;Otherwise, if x does have side effects and corresponds to a ref/out parameter, &lt;STRONG&gt;then a miracle happens&lt;/STRONG&gt;.&lt;/P&gt;&lt;/DIV&gt;
&lt;HR&gt;

&lt;P&gt;Clearly that last bit needed some work.&lt;/P&gt;
&lt;P&gt;So I wrote down all the possible cases I could think of. Clearly x has to be a variable if its type is "reference to variable", so that makes for a small number of cases:&lt;/P&gt;
&lt;HR&gt;

&lt;DIV class=spec&gt;
&lt;P&gt;Otherwise, if x does have side effects and corresponds to a ref/out parameter, then the possible cases are:&lt;/P&gt;
&lt;P&gt;* x is a local variable&lt;BR&gt;* x is a value parameter&lt;BR&gt;* x is an out parameter&lt;BR&gt;* x is a ref parameter&lt;BR&gt;* x is a field of an instance&lt;BR&gt;* x is a static field&lt;BR&gt;* x is an array element&lt;BR&gt;* x is a pointer dereferenced with *&lt;BR&gt;* x is a pointer dereferenced with [ ]&lt;/P&gt;
&lt;P&gt;and for each, a miracle happens.&lt;/P&gt;&lt;/DIV&gt;
&lt;HR&gt;

&lt;P&gt;Again, clearly this is not good enough. I re-examined my list to see if I could eliminate any of these cases. Locals, parameters and&amp;nbsp;static fields never have side effects, so we can eliminate them.&lt;/P&gt;
&lt;P&gt;Also, at this point in our analysis, I knew that pointer dereferences of the form "pointer[index]" had already been rewritten into the form "*(pointer + index)", which meant that in practice, we would never actually hit that last case in this algorithm; the second-last case would take care of both.&lt;/P&gt;
&lt;HR&gt;

&lt;DIV class=spec&gt;
&lt;P&gt;Otherwise, if x does have side effects and corresponds to a ref/out parameter, then the possible cases are:&lt;/P&gt;
&lt;P&gt;* x is a field of an instance&lt;BR&gt;* x is an array element&lt;BR&gt;* x is a pointer dereferenced with *&lt;BR&gt;&lt;BR&gt;and for each, a miracle happens.&lt;/P&gt;&lt;/DIV&gt;
&lt;HR&gt;

&lt;P&gt;I then started to think of what side effects could happen for each.&amp;nbsp;We could have "ref instance.field", "ref array[index]", or "ref *pointer", and&amp;nbsp;"instance", "array", "index" and "pointer" can all be expressions that have a&amp;nbsp;side effect. ("field" cannot, it merely names a field.) So now we can use the same specification as before:&lt;/P&gt;
&lt;HR&gt;

&lt;P class=spec&gt;Otherwise, if x does have side effects and corresponds to a ref/out parameter, then the possible cases are:&lt;/P&gt;
&lt;DIV class=spec&gt;
&lt;UL&gt;
&lt;LI&gt;x is ref/out instance.field: in this case,&amp;nbsp;add var temp=instance&amp;nbsp;to&amp;nbsp;L and ref/out temp.field to A2.&lt;/LI&gt;
&lt;LI&gt;x is ref/out array[index]: in this case, add var t1 = array and&amp;nbsp;var t2 = index to L and ref/out t1[t2] to A2.&lt;/LI&gt;
&lt;LI&gt;x is ref/out *pointer: in this case, add var temp = pointer to L and ref/out *temp to A2.&lt;/LI&gt;&lt;/UL&gt;&lt;/DIV&gt;
&lt;HR&gt;

&lt;P&gt;And now we have something I can implement. So I sent this proposed spec around for review, while I started plugging away at the implementation.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;This spec is wrong.&lt;/STRONG&gt; Can you spot the&amp;nbsp;bugs in my implementation&amp;nbsp;that my coworkers found by reading my spec?&lt;/P&gt;
&lt;P&gt;Next time, the thrilling conclusion.&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9921545" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Code+Quality/default.aspx">Code Quality</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Software+development+methodology/default.aspx">Software development methodology</category></item><item><title>Simple names are not so simple, Part Two, plus, volcanoes and fried foods</title><link>http://blogs.msdn.com/ericlippert/archive/2009/11/05/simple-names-are-not-so-simple-part-two.aspx</link><pubDate>Thu, 05 Nov 2009 14:52:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9909324</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9909324.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9909324</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;I've returned from a brief&amp;nbsp;vacation, visiting friends on the island of Maui. I'd never been to that part of the world before. Turns out, it's a small island in the middle of the Pacific&amp;nbsp;Ocean, entirely made out of volcanoes.&amp;nbsp;Weird!&amp;nbsp;But delightful.&lt;/P&gt;
&lt;P&gt;The most impressive thing about the Hawaiian Islands for me was just how obvious were --&amp;nbsp;even to my completely untrained eyes&amp;nbsp;-- the geomechanical and fluvial processes which shaped the landscape. The mountains and craters and river valleys and red sand beaches and easily-fractured rocks were very different from the (also somewhat volcanic) much older mountainous landscape I've lived in for the past decade.&lt;/P&gt;
&lt;P&gt;Also quite amusing to me was learning to read and pronounce Hawaiian place names. It is all very logical once you know the system; before long I could easily&amp;nbsp;pronounce signs like WAINAPANAPA STATE PARK -- wa-ee-napa-napa&amp;nbsp;--&amp;nbsp;or PUUNENE AVENUE --&amp;nbsp;pu-oo-nay-nay&amp;nbsp;-- or MAILIBEHANAMONOTANA STREET&amp;nbsp;-- "Miley-Stewart-is-really-Hannah-Montana".&lt;/P&gt;
&lt;P&gt;Many thanks to K and R and D for putting me and Leah up for a week; if you're going to Hawai'i and can stay with locals, I highly recommend it, particularly if they are awesome people. Everyone in Maui was awesome, with the exception of the rangers at (stunningly beautiful, even for Maui) Wa'inapanapa State Park, who are apparently consistently grumpy. As one Hawaiian, himself in the camping sector of the economy put it to me, "They do not have&lt;EM&gt; the big aloha&lt;/EM&gt;".&lt;/P&gt;
&lt;P&gt;The most &lt;EM&gt;amusing&lt;/EM&gt; encounter was on the Hana Highway. There are numerous little stops along the way, where someone has erected a hut or parked a trailer and is selling coconuts, smoothies, banana bread, and so on.&amp;nbsp;Hand-lettered signs, stunning natural beauty, middle of nowhere, you get the picture I'm sure. At one of the larger such stops there was a young fellow, probably in his late twenties, serving a variety of fried foods. It was&amp;nbsp;mostly traditional American-style Chinese food, but also he had french fries, fish'n'chips, and so on. He was clearly not a native speaker of English, but spoke understandably with a strong accent. We were waiting behind a middled-aged woman with a typically&amp;nbsp;midwestern American accent. Their conversation went something like this:&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Her:&lt;/STRONG&gt; I'm not very hungry, can I just get the fish without the chips?&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Him, not quite following her:&lt;/STRONG&gt; Half order?&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Her, louder&lt;/STRONG&gt;: How much without the fries?&lt;/P&gt;
&lt;P&gt;This went back and forth for some time, both sides becoming increasingly frustrated by the communication breakdown, until:&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Her, even&amp;nbsp;louder&lt;/STRONG&gt;: Can I speak to your manager?&lt;/P&gt;
&lt;P&gt;Leah and K and I silently&amp;nbsp;&lt;EM&gt;boggled&lt;/EM&gt; -- there is no other word for it -- at each other for a moment. Where on earth did she imagine that&amp;nbsp;a&amp;nbsp;&lt;EM&gt;manager&lt;/EM&gt; was going to emerge from? There was a counter, behind that, a trailer with a wok in it, behind that, &lt;EM&gt;jungle&lt;/EM&gt;, and behind that, &lt;EM&gt;huge jagged lava rocks&lt;/EM&gt; followed immediately by &lt;EM&gt;the Pacific Ocean&lt;/EM&gt;. And what sort of &lt;EM&gt;management structure&lt;/EM&gt; does she&amp;nbsp;think one really needs to manage&amp;nbsp;a single guy selling pineapple fried rice at the side of a highway? My conclusion: &lt;EM&gt;people have strange beliefs. &lt;/EM&gt;Sometimes their beliefs cause them to leave in a huff with neither fish nor chips, even &lt;EM&gt;when fish and chips are both plentiful and reasonably priced&lt;/EM&gt;. Hopefully she had better luck in Hana.&lt;/P&gt;
&lt;P&gt;Anyway, enough travelogue. Regarding the puzzle from last time: the code is correct, and compiles without issue. I was quite surprised when I first learned that; it certainly looks like&amp;nbsp;it violates our rule about not using the same simple name to mean&amp;nbsp;two different things in&amp;nbsp;one block.&lt;/P&gt;
&lt;P&gt;The key is to understanding why this is legal is&amp;nbsp;that the query comprehensions and foreach loops are specified as &lt;EM&gt;syntactic sugars&lt;/EM&gt; for another program, and it is &lt;EM&gt;that&lt;/EM&gt; program which is actually analyzed for correctness. Our original program:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;static void Main()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; int[] data = { 1, 2, 3, 1, 2, 1 };&lt;BR&gt;&amp;nbsp; foreach (var m in from m in data orderby m select m)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; System.Console.Write(m);&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;is transformed into&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;static void Main()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; int[] data = { 1, 2, 3, 1, 2, 1 };&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IEnumerator&amp;lt;int&amp;gt; e = ((IEnumerable&amp;lt;int&amp;gt;)(data.OrderBy(m=&amp;gt;m)).GetEnumerator();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; try&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; int m;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; while(e.MoveNext())&lt;BR&gt;&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; m = (int)(int)e.Current;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.Write(m);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; finally&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (e != null) ((IDisposable)e).Dispose();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;BR&gt;&amp;nbsp;&lt;BR&gt;&lt;/SPAN&gt;There are five usages of m in this transformed program; it is:&lt;/P&gt;
&lt;P&gt;1) declared as the formal parameter of a lambda.&lt;BR&gt;2) used in the body of the lambda; here it refers to the formal parameter.&lt;BR&gt;3) declared as a local variable&lt;BR&gt;4) written to in the loop; here it refers to the local variable&lt;BR&gt;5) read from in the loop; here it refers to the local variable&lt;/P&gt;
&lt;P&gt;Is there any usage of a local variable before its declaration? No. &lt;/P&gt;
&lt;P&gt;Are there any two declarations that have the same name in the same declaration space? It would appear so. The body of Main defines a local variable declaration space, and clearly the body of Main contains, indirectly, two declarations for m, one as a formal lambda parameter and one as a local. But I said last time that local variable declaration spaces have special rules for determining overlaps. It is illegal for a local variable declaration space to directly contain a declaration such that another nested local variable declaration space contains a declaration of the same name. But an outer declaration space which indirectly contains two such declarations is not&amp;nbsp; an error. So in this case, no, there are no local variable declarations spaces which directly contain a declaration for m, such that a nested local variable declaration space also directly contains a declaration for m. Our two local variable declarations spaces which directly contain a declaration for m do not overlap anywhere.&lt;/P&gt;
&lt;P&gt;Is there any declaration space which contains two inconsistent usages of the simple name m? Yes, again, the outer block of Main contains two inconsistent usages of m. But again, this is not relevant. The question is whether any declaration space directly containing m has an inconsistent usage. Again, we have two declaration spaces but they do not overlap each other, so there's no problem here either.&lt;/P&gt;
&lt;P&gt;The thing which makes this legal, interestingly enough, is the generation of the loop variable declaration logically within the try block. Were it to be generated outside the try block then this would be a violation of the rule about inconsistent usage of a simple name throughout a declaration space.&lt;BR&gt;&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9909324" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Dialogue/default.aspx">Dialogue</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/declaration+spaces/default.aspx">declaration spaces</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/scope/default.aspx">scope</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/customer+service/default.aspx">customer service</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Simple+Names/default.aspx">Simple Names</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/maui/default.aspx">maui</category></item><item><title>Simple names are not so simple</title><link>http://blogs.msdn.com/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx</link><pubDate>Mon, 02 Nov 2009 14:23:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9909292</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>14</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9909292.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9909292</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;C# has many rules that are designed to prevent some common sources of bugs and encourage good programming practices. So many, in fact, that it is often quite confusing to sort out exactly which rule has been violated. I thought I might spend some time talking about what the different rules are. We'll finish up with a puzzle.&lt;/P&gt;
&lt;P&gt;To begin with, it will be vital to understand &lt;A href="http://blogs.msdn.com/ericlippert/archive/2009/08/03/what-s-the-difference-part-two-scope-vs-declaration-space-vs-lifetime.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2009/08/03/what-s-the-difference-part-two-scope-vs-declaration-space-vs-lifetime.aspx"&gt;the difference between &lt;EM&gt;scope&lt;/EM&gt; and &lt;EM&gt;declaration space&lt;/EM&gt;&lt;/A&gt;. To refresh your memory of my earlier article: the &lt;EM&gt;scope&lt;/EM&gt; of an entity is &lt;EM&gt;the region of text in which that entity may be referred to by its unqualified name&lt;/EM&gt;. A &lt;EM&gt;declaration space&lt;/EM&gt; is a region of text in which &lt;EM&gt;no two things may have the same name &lt;/EM&gt;(with an exception for methods which differ by signature.) A "local variable declaration space" is a particular kind of declaration space used for declaring local variables; local variable declaration spaces have special rules for determining when they overlap.&lt;/P&gt;
&lt;P&gt;The next thing that you have to understand to make any sense o this is what a "simple name" is. A &lt;EM&gt;simple name&lt;/EM&gt; is always either just a plain identifier, like "x", or, in some cases, a plain identifier followed by a type argument list, like "Frob&amp;lt;int, string&amp;gt;". &lt;/P&gt;
&lt;P&gt;Lots of things are treated as "simple names" by the compiler: local variable declarations, lambda parameters, and so on, always have the first form of simple name in their declarations. When you say "Console.WriteLine(x);" the "Console" and "x" are simple names but the "WriteLine" is not. Confusingly, there are some textual entities which have the form of simple names, but are not treated as simple names by the compiler. We might talk about some of those situations in later fabulous adventures.&lt;/P&gt;
&lt;P&gt;So, without further ado, here are some relevant rules which are frequently confused. It's rules 3 and 4 that people find particularly confusing.&lt;/P&gt;
&lt;P&gt;1) It is illegal to refer to a local variable before its declaration. (This seems reasonable I hope.)&lt;BR&gt;2) It is illegal to have two local variables of the same name in the same local variable declaration space or nested local variable declaration spaces.&lt;BR&gt;3) Local variables are in scope throughout the entire block in which the declaration occurs. This is in contrast with C++, in which local variables are in scope in their block only at points after the declaration.&lt;BR&gt;4) For every occurrence of a simple name, whether in a declaration or as part of an expression, all uses of that simple name within the immediately enclosing local variable declaration space must refer to the same entity.&lt;/P&gt;
&lt;P&gt;The purpose of all of these rules is to prevent the class of bugs in which the reader/maintainer of the code is tricked into believing they are referring to one entity with a simple name, but are in fact accidentally referring to another entity entirely. These rules are in particular designed to prevent nasty surprises when performing what ought to be safe refactorings. &lt;/P&gt;
&lt;P&gt;Consider a world in which we did not have rules 3 and 4. In that world, this code would be legal:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;class C&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; int x;&lt;BR&gt;&amp;nbsp; void M()&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // 100 lines of code&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; x = 20; // means "this.x";&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(x); // means "this.x"&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // 100 lines of code&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; int x = 10;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(x); // means "local x"&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;This is hard on the person reading the code, who has a reasonable expectation that the two "Console.WriteLine(x)" lines do in fact both print out the contents of the same variable. But it is particularly nasty for the maintenance programmer who wishes to impose a reasonable coding standard upon this body of code. "Local variables are declared at the top of the block where they're used" is a reasonable coding standard in a lot of shops. But changing the code to:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;class C&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; int x;&lt;BR&gt;&amp;nbsp; void M()&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; int x;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // 100 lines of code&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; x = 20; // no longer means "this.x";&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(x); // no longer means "this.x"&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // 100 lines of code&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; x = 10;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(x); // means "local x"&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;} &lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;changes the meaning of the code! We wish to discourage authoring of multi-hundred-line methods, but making it harder and more error-prone to refactor them into something cleaner is not a good way to achieve that goal.&lt;/P&gt;
&lt;P&gt;Notice that the original version of this program, rule 3 means that the program violates rule 1 -- the first usage of "x" is treated as a reference to the local before it is declared. The fact that it violates rule 1 because of rule 3 is precisely what prevents it from being a violation of rule 4! The meaning of "x" is consistent throughout the block; it always means the local, and therefore is sometimes used before it is declared. If we scrapped rule 3 then this would be a violation of rule 4, because we would then have two inconsistent meanings for the simple name "x" within one block.&lt;/P&gt;
&lt;P&gt;Now, these rules do not mean that you can refactor willy-nilly. We can still construct situations in which similar refactorings fail. For example:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;class C&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; int x;&lt;BR&gt;&amp;nbsp; void M()&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // 100 lines of code&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x = 20; // means "this.x";&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(x); // means "this.x"&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // 100 lines of code&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; int x = 10;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(x); // means "local x"&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;This is perfectly legal. We have the same simple name being used two different ways in two different blocks, but the immediately enclosing block of each usage does not overlap that of any other usage. The local variable is in scope throughout its immediately enclosing block, but that block does not overlap the block above. In this case, it is safe to refactor the declaration of the local to the top of its block, but not safe to refactor the declaration to the top of the outermost block; that would change the meaning of "x" in the first block. Moving a declaration up is almost always a safe thing to do; moving it out is not necessarily safe. &lt;/P&gt;
&lt;P&gt;Now that you know all that, here's a puzzle for you, a puzzle that I got completely wrong the first time I saw it:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;using System.Linq;&lt;BR&gt;class Program&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; static void Main()&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; int[] data = { 1, 2, 3, 1, 2, 1 };&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; foreach (var m in from m in data orderby m select m)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; System.Console.Write(m);&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;It certainly looks like name "m" is being used multiple times to mean different things. Is this program legal? If yes, why do the rules for not re-using simple names&amp;nbsp;not apply? If no, precisely what rule has been violated?&amp;nbsp; &lt;/P&gt;
&lt;P&gt;[Eric is on vacation; this posting was pre-recorded.]&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9909292" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Language+Design/default.aspx">Language Design</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/declaration+spaces/default.aspx">declaration spaces</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/scope/default.aspx">scope</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Simple+Names/default.aspx">Simple Names</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/local+variables/default.aspx">local variables</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/refactoring/default.aspx">refactoring</category></item><item><title>Color Color</title><link>http://blogs.msdn.com/ericlippert/archive/2009/07/06/color-color.aspx</link><pubDate>Mon, 06 Jul 2009 16:29:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9762614</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>24</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9762614.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9762614</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;Pop quiz: What does the following code do when compiled and run?&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;class C&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static void M(string x)&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; System.Console.WriteLine("static M(string)");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void M(object s)&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; System.Console.WriteLine("M(object)");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;BR&gt;}&lt;BR&gt;class Program&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; static void Main()&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; C c = new C();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c.M("hello");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;(1) writes static M(string)&lt;BR&gt;(2) writes M(object)&lt;BR&gt;(3) uh, dude, this code doesn’t even compile much less run&lt;BR&gt;(4) something else 
&lt;P&gt;Think about that for a bit and then try it and see if you were right. 
&lt;P&gt;. 
&lt;P&gt;. 
&lt;P&gt;. 
&lt;P&gt;. 
&lt;P&gt;. 
&lt;P&gt;. 
&lt;P&gt;. 
&lt;P&gt;In option (1), the compiler could decide that the best match is the static one and let you call it through the instance, ignoring the instance value. In option (2), the compiler could decide that the object version is the best match and ignore the static one, even though the argument match is better. But neither of those actually happens; the rules of C# say that the compiler should &lt;STRONG&gt;pick the best match based on the arguments&lt;/STRONG&gt;, and &lt;EM&gt;then&lt;/EM&gt; disallow static calls that are through an instance! The actual result here is therefore (3): &lt;SPAN class=code&gt;
&lt;P&gt;error CS0176: Member 'C.M(string)' cannot be accessed with an instance reference; qualify it with a type name instead &lt;/SPAN&gt;
&lt;P&gt;What is up with this craziness? If you believe that the rule “static methods should never be accessed through instances” is a good rule – and it seems reasonable – then why doesn’t overload resolution remove the static methods from the candidate set when called through an instance? Why does it even allow the “string” version to be an applicable candidate in the first place, if the compiler knows that it can never possibly work? 
&lt;P&gt;I agree that this seems really goofy at first. 
&lt;P&gt;To explain why this is not quite as dumb as it seems, consider the following variation on the problem. Class C stays the same. &lt;SPAN class=code&gt;
&lt;P&gt;class B&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; public C C = new C();&lt;BR&gt;&amp;nbsp; public void N()&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; C.M("hello");&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;What does a call to N on an instance of B do?&lt;/P&gt;
&lt;P&gt;(1) writes static M(string)&lt;BR&gt;(2) writes M(object)&lt;BR&gt;(3) compilation error&lt;BR&gt;(4) something else&lt;/P&gt;
&lt;P&gt;.&lt;/P&gt;
&lt;P&gt;.&lt;/P&gt;
&lt;P&gt;.&lt;/P&gt;
&lt;P&gt;.&lt;/P&gt;
&lt;P&gt;.&lt;/P&gt;
&lt;P&gt;.&lt;/P&gt;
&lt;P&gt;A bit trickier now, isn’t it? Does C.M mean “call instance method M on the instance stored in this.C?” or does it mean “call static method M on type C”? Both are applicable!&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Because of our goofy rule we do the right thing in this case.&lt;/STRONG&gt; We first resolve the call based solely on the arguments and determine that the static method is the best match. Then we check to see if the “receiver” at the call site can be interpreted as being through the type. It can. So we make the static call and write “static M(string)”. &lt;STRONG&gt;If the instance version had been the best match then we would successfully call the instance method through the property.&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;So the reason that the compiler does not remove static methods when calling through an instance is because the compiler does not necessarily know that you are calling through an instance. Because there are situations where it is ambiguous whether you’re calling through an instance or a type, we defer deciding which you meant until the best method has been selected.&lt;/P&gt;
&lt;P&gt;Now, one could make the argument that in our first case, the receiver cannot &lt;EM&gt;possibly&lt;/EM&gt; be a type. We &lt;EM&gt;could&lt;/EM&gt; have further complicated the language semantics by having &lt;EM&gt;three&lt;/EM&gt; overload resolution rules, one for when the receiver is &lt;EM&gt;known to be a type&lt;/EM&gt;, one for when the receiver is &lt;EM&gt;known to not be a type&lt;/EM&gt;, and one for when the receiver &lt;EM&gt;might or might not be a type&lt;/EM&gt;. But rather than complicate the language further, we made the pragmatic choice of simply deferring the staticness check until after the bestness check. That’s not perfect but it is good enough for most cases and it solves the common problem.&lt;/P&gt;
&lt;P&gt;The common problem is the situation that arises when you have a&lt;STRONG&gt; property of a type with the same name&lt;/STRONG&gt;, and then try to call either a static method on the type, or an instance method on the property. (This can also happen with locals and fields, but local and field names typically differ&amp;nbsp;in case from the names of their&amp;nbsp;types.)&amp;nbsp;The canonical motivating example is a public property named Color of type Color, so we call this “&lt;STRONG&gt;the Color Color problem&lt;/STRONG&gt;”. &lt;/P&gt;
&lt;P&gt;In real situations the instance and static methods typically have different names, so in the typical scenario you never end up calling an instance method when you expect to call a static method, or vice versa. The case I presented today with a name collision between a static and an instance method is relatively rare.&lt;/P&gt;
&lt;P&gt;If you’re interested in reading the exact rules for how the compiler deals with the Color Color problem, see section 7.5.4.1 of the C# 3.0 specification. &lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9762614" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Static+Methods/default.aspx">Static Methods</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Language+Design/default.aspx">Language Design</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Overload+Resolution/default.aspx">Overload Resolution</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Color+Color/default.aspx">Color Color</category></item><item><title>What Would Tufte Do?</title><link>http://blogs.msdn.com/ericlippert/archive/2009/05/27/what-would-tufte-do.aspx</link><pubDate>Wed, 27 May 2009 17:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9634147</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>10</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9634147.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9634147</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;What is this a chart of? I'll post the answer tomorrow.&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/ericlippert/WindowsLiveWriter/WhenFiveHundredPostsYouReach_7890/blogchart_2.jpg" mce_href="http://blogs.msdn.com/blogfiles/ericlippert/WindowsLiveWriter/WhenFiveHundredPostsYouReach_7890/blogchart_2.jpg"&gt;&lt;IMG title="mysterious chart" style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; DISPLAY: block; FLOAT: none; MARGIN-LEFT: auto; BORDER-LEFT: 0px; MARGIN-RIGHT: auto; BORDER-BOTTOM: 0px" height=276 alt="mysterious chart" src="http://blogs.msdn.com/blogfiles/ericlippert/WindowsLiveWriter/WhenFiveHundredPostsYouReach_7890/blogchart_thumb.jpg" width=642 border=0 mce_src="http://blogs.msdn.com/blogfiles/ericlippert/WindowsLiveWriter/WhenFiveHundredPostsYouReach_7890/blogchart_thumb.jpg"&gt;&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;UPDATE: Someone has &lt;EM&gt;already&lt;/EM&gt; correctly deduced the answer. (And man, that was fast!)&amp;nbsp;So don't read the comments if you don't want spoilers.&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9634147" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category></item><item><title>Comma Quibbling</title><link>http://blogs.msdn.com/ericlippert/archive/2009/04/15/comma-quibbling.aspx</link><pubDate>Wed, 15 Apr 2009 17:06:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9549611</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>268</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9549611.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9549611</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;[UPDATE: Holy goodness. Apparently this was a more popular pasttime than I anticipated. There's like a hundred solutions in there. Who knew there were that many ways to stick commas in a string? It will take me some time to go through them all, so don't be surprised if it's a couple of weeks until I get them all sorted out.]&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/ericlippert/WindowsLiveWriter/CommaQuibbling_DE57/Comma_2.jpg" mce_href="http://blogs.msdn.com/blogfiles/ericlippert/WindowsLiveWriter/CommaQuibbling_DE57/Comma_2.jpg"&gt;&lt;IMG title=Comma style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; DISPLAY: inline; MARGIN-LEFT: 0px; BORDER-LEFT: 0px; MARGIN-RIGHT: 0px; BORDER-BOTTOM: 0px" height=128 alt=Comma src="http://blogs.msdn.com/blogfiles/ericlippert/WindowsLiveWriter/CommaQuibbling_DE57/Comma_thumb.jpg" width=93 align=left border=0 mce_src="http://blogs.msdn.com/blogfiles/ericlippert/WindowsLiveWriter/CommaQuibbling_DE57/Comma_thumb.jpg"&gt;&lt;/A&gt; The point of Monday’s post about comma-separated lists was not so much about the actual problem; it’s a rather trivial problem. Rather, I wanted to make two points. First, stating the &lt;EM&gt;actual problem&lt;/EM&gt; rather than a much harder and more general version of the problem is likely to get you a realistic solution to your actual problem much faster. And second, reworking the statement of the problem into an equivalent but structurally different statement is a great way to see solutions that you might have otherwise missed.&lt;/P&gt;
&lt;P&gt;But whenever I make a post illustrating such points with a specific example, lots of people pipe up with their ideas for how to solve the specific example. Which is awesome; I encourage this behaviour.&lt;/P&gt;
&lt;P&gt;So in that spirit, here’s a slightly harder version of the string concatenation problem, just for the fun of it. Write me a function that takes a non-null IEnumerable&amp;lt;string&amp;gt; and returns a string with the following characteristics:&lt;/P&gt;
&lt;P&gt;(1) If the sequence is empty then the resulting string is "{}".&lt;BR&gt;(2) If the sequence is a single item "ABC" then the resulting string is "{ABC}".&lt;BR&gt;(3) If the sequence is the two item sequence "ABC", "DEF" then the resulting string is "{ABC and DEF}".&lt;BR&gt;(4) If the sequence has more than two items, say, "ABC", "DEF", "G", "H" then the resulting string is "{ABC, DEF, G and H}". (Note: no Oxford comma!)&lt;/P&gt;
&lt;P&gt;I think you get the idea. You can post your solution in the comments or use the link on the blog page to email your solution to me.&lt;/P&gt;
&lt;P&gt;The strings in the sequence can be assumed to be non-null but can otherwise be any string value, including empty strings or strings containing commas, braces and "and". &lt;/P&gt;
&lt;P&gt;There’s no size limit on the sequence; it could be tiny, it could be thousands of strings. But it will be finite.&lt;/P&gt;
&lt;P&gt;All you get are the methods of IEnumerable&amp;lt;string&amp;gt;; if you want to make that thing into a list or an array, you’re going to need to do that explicitly rather than casting it and hoping for the best.&lt;/P&gt;
&lt;P&gt;I am particularly interested in solutions which make the semantics of the code very clear to the code maintainer.&lt;/P&gt;
&lt;P&gt;Of course, C# is most interesting to me, but if there are neat ways to express this in other languages, I’d love to see them too.&lt;/P&gt;
&lt;P&gt;If there are any particularly amusing or interesting implementations I’ll dissect them on the blog in a future episode, probably in a week or so. I’m not going to have time to do a detailed analysis of every one.&lt;/P&gt;
&lt;P&gt;And… go!&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9549611" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category></item><item><title>Mutating Readonly Structs </title><link>http://blogs.msdn.com/ericlippert/archive/2008/05/14/mutating-readonly-structs.aspx</link><pubDate>Wed, 14 May 2008 17:10:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8481327</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>27</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/8481327.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=8481327</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;Consider this program which attempts to mutate a readonly mutable struct. What happens?&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;struct Mutable {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; private int x;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public int Mutate()&amp;nbsp;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.x = this.x + 1;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return this.x;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;
&lt;P&gt;class Test {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public readonly Mutable m = new Mutable();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; static void Main(string[] args)&amp;nbsp;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Test t = new Test();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; System.Console.WriteLine(t.m.Mutate());&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; System.Console.WriteLine(t.m.Mutate());&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; System.Console.WriteLine(t.m.Mutate());&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;There are a number of things this program could do. Does it:&lt;/P&gt;
&lt;P&gt;1)&amp;nbsp;Print 1, 2, 3 -- because m is readonly, but the "readonly" only applies to m, not to its contents. &lt;BR&gt;2) Print 0, 0, 0 -- because m is readonly, x cannot be changed. It always has its default value of zero.&lt;BR&gt;3) Throw an exception at runtime, when the attempt is made to mutate the contents of a readonly field.&lt;BR&gt;4) Do something else&lt;/P&gt;
&lt;P&gt;?&lt;/P&gt;
&lt;P&gt;People are frequently surprised to learn that the answer is (4). In fact, this prints 1, 1, 1.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Why?&lt;/P&gt;
&lt;P&gt;Because, remember, accessing a value type gives you a COPY of the value. When you say t.m, you get a copy of whatever is presently stored in m. m is immutable, but the copy is not. The copy is then mutated, and the value of x in the copy is returned.&amp;nbsp;But m remains untouched.&lt;/P&gt;
&lt;P mce_keep="true"&gt;The relevant section of the specification is 7.5.4, which states that&amp;nbsp;when resolving "E.I" where E is an object and I is a field...&lt;/P&gt;&lt;SPAN class=spec&gt;
&lt;P&gt;...if the field is readonly and the reference occurs outside an instance constructor of the class in which the field is declared, then the result is a value, namely the value of the field I in the object referenced by E.&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;The important word here is that the result is the &lt;EM&gt;value&lt;/EM&gt; of the field,&amp;nbsp;not the &lt;EM&gt;variable&lt;/EM&gt; associated with the field. &lt;EM&gt;Readonly fields are not variables outside of the constructor&lt;/EM&gt;. (&lt;A class="" href="http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx" target=_blank mce_href="http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx"&gt;The initializer here&amp;nbsp;is considered to be inside the constructor; see my earlier post on that subject&lt;/A&gt;.)&lt;/P&gt;
&lt;P mce_keep="true"&gt;Great. What about that second dot, as in ".Mutate()"?&amp;nbsp; We look&amp;nbsp;at section 7.4.4 to find out how to invoke E.M():&lt;/P&gt;&lt;SPAN class=spec&gt;
&lt;P&gt;If E is not classified as a variable, then a temporary local variable&amp;nbsp;of E's type is created and the value of E is assigned to that variable. E is then reclassified as a reference to that temporary local variable. The temporary variable is accessible as &lt;EM&gt;this&lt;/EM&gt; within M, but not in any other way. Thus, only when E is a true variable is it possible for the&amp;nbsp;caller to observe the changes that M makes to &lt;EM&gt;this&lt;/EM&gt;.&lt;/P&gt;&lt;/SPAN&gt;
&lt;P mce_keep="true"&gt;And there you go. Value semantics are tricky!&lt;/P&gt;
&lt;P mce_keep="true"&gt;This is yet another reason why mutable value types are evil. Try to always make value types immutable.&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8481327" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Immutability/default.aspx">Immutability</category></item><item><title>Why Do Initializers Run In The Opposite Order As Constructors? Part Two</title><link>http://blogs.msdn.com/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx</link><pubDate>Mon, 18 Feb 2008 18:25:12 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7724412</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>42</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/7724412.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=7724412</wfw:commentRss><description>&lt;div class="mine"&gt; &lt;p&gt;As you might have figured out, the answer to last week's puzzle is "if the constructors and initializers run in their actual order then an initialized readonly field of reference type is guaranteed to be non null in any possible call. That guarantee cannot be met if the initializers run in the expected order." &lt;p&gt;Suppose counterfactually that initializers ran in the expected order, that is, derived class initializers run after the base class constructor body. Consider the following pathological cases:&lt;/p&gt;&lt;span class="code"&gt; &lt;p&gt;class Base&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static ThreadsafeCollection t = new ThreadsafeCollection();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public Base()&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; Console.WriteLine("Base constructor");&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (this is Derived) (this as Derived).DoIt(); &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // would deref null if we are constructing an instance of Derived&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Blah(); &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // would deref null if we are constructing an instance of MoreDerived&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; t.Add(this);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // would deref null if another thread calls Base.t.GetLatest().Blah();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // before derived constructor runs&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public virtual void Blah() { }&lt;br&gt;} &lt;br&gt;class Derived : Base&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; readonly Foo derivedFoo = new Foo("Derived initializer");&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public DoIt()&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; derivedFoo.Bar();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br&gt;}&lt;br&gt;class MoreDerived : Derived&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public override void Blah() { DoIt(); }&lt;br&gt;} &lt;br&gt;&lt;br&gt;&lt;/span&gt;Calling methods on derived types from constructors is dirty pool, but it is not illegal. And stuffing not-quite-constructed objects into global state is risky, but not illegal. I'm not recommending that you do any of these things -- please, do not, for the good of us all. I'm saying that it would be really nice if we could give you an ironclad guarantee that an initialized readonly field is always observed in its initialized state, and we cannot make that guarantee unless we run all the initializers first, and then all of the constructor bodies.&lt;/p&gt; &lt;p&gt;Note that of course, if you initialize your readonly fields in the constructor, then all bets are off. We make no guarantees as to the fields not being accessed before the constructor bodies run. &lt;/p&gt; &lt;p&gt;Next time on FAIC: how to get a question &lt;em&gt;not&lt;/em&gt; answered.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7724412" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Immutability/default.aspx">Immutability</category></item><item><title>Why Do Initializers Run In The Opposite Order As Constructors? Part One</title><link>http://blogs.msdn.com/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx</link><pubDate>Sat, 16 Feb 2008 02:01:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7724010</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>34</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/7724010.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=7724010</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;Pop quiz! 
&lt;P&gt;What do you expect the output of this program to be? 
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;using System; 
&lt;P&gt;class Foo&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public Foo(string s)&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; Console.WriteLine("Foo constructor: {0}", s);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void Bar() { }&lt;BR&gt;} &lt;BR&gt;class Base&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; readonly Foo baseFoo = new Foo("Base initializer");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public Base()&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; Console.WriteLine("Base constructor");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;} &lt;BR&gt;class Derived : Base&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; readonly Foo derivedFoo = new Foo("Derived initializer");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public Derived()&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; Console.WriteLine("Derived constructor");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;} &lt;BR&gt;static class Program&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; static void Main()&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; new Derived();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;} &lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;I got a question from a user recently noting that the order was not as he expected. One naively expects that the order will go "base initializers, base constructor body, derived initializers, derived constructor body". In fact the order actually is that first all the initializers run in order &lt;EM&gt;from derived to base&lt;/EM&gt;, and then all the constructor bodies run in order &lt;EM&gt;from base to derived&lt;/EM&gt;. 
&lt;P&gt;The latter bit makes perfect sense; the more derived constructors may rely upon state initialized by the less derived constructors, so the constructors should run in order from base to derived. But most people assume that the call sequence of the code above is equivalent to this pseudocode: &lt;SPAN class=code&gt;
&lt;P&gt;// Expected&lt;BR&gt;BaseConstructor()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ObjectConstructor();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; baseFoo = new Foo("Base initializer");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine("Base constructor");&lt;BR&gt;} &lt;BR&gt;DerivedConstructor()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; BaseConstructor();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; derivedFoo = new Foo("Derived initializer");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine("Derived constructor");&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;When in point of fact it is equivalent to this:&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;SPAN class=code&gt;// Actual&lt;BR&gt;BaseConstructor()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; baseFoo = new Foo("Base initializer");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ObjectConstructor();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine("Base constructor");&lt;BR&gt;} &lt;BR&gt;DerivedConstructor()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; derivedFoo = new Foo("Derived initializer");&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; BaseConstructor();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine("Derived constructor");&lt;BR&gt;} &lt;/SPAN&gt;&lt;/P&gt;
&lt;P&gt;That explains the &lt;EM&gt;mechanism&lt;/EM&gt; whereby the initializers run in order from derived to base and the constructor bodies run in the opposite order, but why did we choose to implement that mechanism instead of the more intuitively obvious former way? 
&lt;P&gt;Puzzle that one over for a bit, and then read on for a hint. 
&lt;P&gt;... 
&lt;P&gt;... 
&lt;P&gt;... 
&lt;P&gt;The "readonly" modifiers in there were no accident. The code gives the appearance that any call to &lt;SPAN class=code&gt;derivedFoo.Bar()&lt;/SPAN&gt; and &lt;SPAN class=code&gt;baseFoo.Bar()&lt;/SPAN&gt; should never fail with a null dereference exception because both are readonly fields initialized to non-null values. 
&lt;OL&gt;
&lt;LI&gt;Is that appearance accurate, or misleading?&lt;/LI&gt;
&lt;LI&gt;Now suppose initializers ran in the "expected" order and answer question (1) again.&amp;nbsp; &lt;/LI&gt;&lt;/OL&gt;
&lt;P&gt;I'll post the answers and analysis next week. Have a fabulous weekend! 
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7724010" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Immutability/default.aspx">Immutability</category></item><item><title>Psychic Debugging, Part Two</title><link>http://blogs.msdn.com/ericlippert/archive/2007/09/06/psychic-debugging-part-two.aspx</link><pubDate>Thu, 06 Sep 2007 18:31:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:4789522</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/4789522.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=4789522</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;A number of readers have the &lt;A class="" href="http://blogs.msdn.com/ericlippert/archive/2004/08/20/i-have-a-mysterious-fifth-sense.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2004/08/20/i-have-a-mysterious-fifth-sense.aspx"&gt;mysterious fifth sense&lt;/A&gt; which gives them the ability to deduce that the &lt;SPAN class=code&gt;GetBars&lt;/SPAN&gt; method from &lt;A class="" href="http://blogs.msdn.com/ericlippert/archive/2007/09/05/psychic-debugging-part-one.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2007/09/05/psychic-debugging-part-one.aspx"&gt;yesterday's post&lt;/A&gt; contains a &lt;SPAN class=code&gt;yield return&lt;/SPAN&gt; and is therefore an iterator. Remember, as the standard states (in section 10.14.4):&lt;/P&gt;&lt;SPAN class=spec&gt;
&lt;P&gt;[...] execution of the code in the iterator block occurs when the enumerator object's MoveNext method is invoked.&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;Since the test program does not invoke &lt;SPAN class=code&gt;MoveNext&lt;/SPAN&gt;, the check for &lt;SPAN class=code&gt;null&lt;/SPAN&gt; is never executed, and therefore the exception is never thrown.&lt;/P&gt;
&lt;P&gt;Since most of the interesting new sequence operators available in C# 3.0 are implemented with iterators it probably will be increasingly important for developers to understand a bit more about how iterators work behind the scenes. I may do some blog posts on that over the next little while.&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=4789522" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Psychic+Debugging/default.aspx">Psychic Debugging</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category></item><item><title>Psychic Debugging, Part One</title><link>http://blogs.msdn.com/ericlippert/archive/2007/09/05/psychic-debugging-part-one.aspx</link><pubDate>Wed, 05 Sep 2007 20:30:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:4766755</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/4766755.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=4766755</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;Here is a compiler bug report I got the other day. The user is trying to write a unit test for a method which takes a &lt;SPAN class=code&gt;Foo&lt;/SPAN&gt; and returns a collection of &lt;SPAN class=code&gt;Bar&lt;/SPAN&gt;s. The test is supposed to confirm that &lt;SPAN class=code&gt;GetBars&lt;/SPAN&gt; throws an exception if the argument is &lt;SPAN class=code&gt;null&lt;/SPAN&gt;. The test was failing with “got no exception”. The user was wondering if somehow the compiler had optimized away the call.&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; static void Test()&amp;nbsp;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; bool gotException = false;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; try {&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; IEnumerable&amp;lt;Bar&amp;gt; bars = Foo.GetBars(null);&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; catch (ArgumentNullException ex) {&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; Console.WriteLine("SUCCESS: Got expected exception");&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; gotException = true;&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; catch (Exception ex) {&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; Console.WriteLine("FAILURE: Got unexpected exception");&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; gotException = true;&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; finally {&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; if (!gotException)&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;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine("FAILURE: Got no exception");&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;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;Several people (including myself and &lt;A class="" href="http://blogs.msdn.com/cyrusn/" mce_href="http://blogs.msdn.com/cyrusn/"&gt;Cyrus&lt;/A&gt;) psychically debugged this one independently. The user did not include the source code of &lt;SPAN class=code&gt;GetBars&lt;/SPAN&gt;, which is what necessitated the use of our psychic powers. Because I am a nice guy, I will give you the beginning:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; static public IEnumerable&amp;lt;Bar&amp;gt; GetBars(Foo foo)&amp;nbsp;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (foo == null) &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; throw new ArgumentNullException("foo");&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;&lt;STRONG&gt;Our psychic powers correctly told us that the behaviour of the test program is correct and expected.&lt;/STRONG&gt; What do your psychic powers tell you about the rest of the implementation of &lt;SPAN class=code&gt;GetBars&lt;/SPAN&gt;? What is going on here?&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=4766755" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Psychic+Debugging/default.aspx">Psychic Debugging</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category></item><item><title>An Inheritance Puzzle, Part Two</title><link>http://blogs.msdn.com/ericlippert/archive/2007/07/30/an-inheritance-puzzle-part-two.aspx</link><pubDate>Mon, 30 Jul 2007 17:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:4089673</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>13</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/4089673.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=4089673</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P minmax_bound="true"&gt;Today, the answer to &lt;A class="" href="http://blogs.msdn.com/ericlippert/archive/2007/07/27/an-inheritance-puzzle-part-one.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2007/07/27/an-inheritance-puzzle-part-one.aspx"&gt;Friday's puzzle&lt;/A&gt;.&amp;nbsp;It prints "Int32". But why?&lt;/P&gt;
&lt;P minmax_bound="true"&gt;Some readers hypothesized that &lt;SPAN class=code&gt;M&lt;/SPAN&gt; would print out "Int32" because the declaration &lt;SPAN class=code&gt;B : A&amp;lt;int&amp;gt;&lt;/SPAN&gt; somehow tells &lt;SPAN class=code&gt;B&lt;/SPAN&gt; that &lt;SPAN class=code&gt;T&lt;/SPAN&gt; is to be treated as &lt;SPAN class=code&gt;int&lt;/SPAN&gt;, now and forever. Though the &lt;EM&gt;answer&lt;/EM&gt; is right, the &lt;EM&gt;explanation&lt;/EM&gt; is not quite right. One can illustrate this by taking &lt;SPAN class=code&gt;C&lt;/SPAN&gt; out of the picture. If you say &lt;SPAN class=code&gt;(new A&amp;lt;string&amp;gt;.B()).M()&lt;/SPAN&gt;, you'll get "String". The fact that &lt;SPAN class=code&gt;B&lt;/SPAN&gt; is an &lt;SPAN class=code&gt;A&amp;lt;int&amp;gt;&lt;/SPAN&gt; doesn't make &lt;SPAN class=code&gt;T&lt;/SPAN&gt; always &lt;SPAN class=code&gt;int&lt;/SPAN&gt; inside &lt;SPAN class=code&gt;B&lt;/SPAN&gt;!&lt;/P&gt;
&lt;P minmax_bound="true"&gt;The always-keen Stuart Ballard was the first to put his finger upon the real crux of the problem -- but&amp;nbsp;he's seen this problem before, so he had an advantage. Eamon Nerbonne was the first to post&amp;nbsp;a complete and&amp;nbsp;correct explanation.&lt;/P&gt;
&lt;P minmax_bound="true"&gt;The really thorny issue here is that the declaration &lt;SPAN class=code&gt;class C : B&lt;/SPAN&gt; is upon close inspection, somewhat ambiguous. Is that equivalent to &lt;SPAN class=code&gt;class C : A&amp;lt;T&amp;gt;.B&lt;/SPAN&gt; or &lt;SPAN class=code&gt;class C : A&amp;lt;int&amp;gt;.B&lt;/SPAN&gt;? &lt;/P&gt;
&lt;P minmax_bound="true"&gt;Clearly it matters which we choose. A method group can only be treated as a member if the method is on a &lt;EM&gt;base class&lt;/EM&gt;. Merely being on an &lt;EM&gt;outer class&lt;/EM&gt; doesn't cut it:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P minmax_bound="true"&gt;public class&amp;nbsp;X { public void M(){} }&lt;BR&gt;public class&amp;nbsp;Y {&lt;BR&gt;&amp;nbsp; public void N() {}&lt;BR&gt;&amp;nbsp; public class Z : X&amp;nbsp;{}&lt;BR&gt;}&lt;BR&gt;...&lt;BR&gt;(new&amp;nbsp;Y.Z()).M(); // legal, from base class&lt;BR&gt;(new Y.Z()).N(); // illegal -- outer class members are not members of inner classes.&lt;/P&gt;&lt;/SPAN&gt;
&lt;P minmax_bound="true"&gt;In our example, when we called &lt;SPAN class=code&gt;M&lt;/SPAN&gt; on an instance of&amp;nbsp;&lt;SPAN class=code&gt;A&amp;lt;string&amp;gt;.B.C&lt;/SPAN&gt;,&amp;nbsp;it was calling a method&amp;nbsp;of the base class of &lt;SPAN class=code&gt;C&lt;/SPAN&gt;. If the base class of &lt;SPAN class=code&gt;C&lt;/SPAN&gt; is &lt;SPAN class=code&gt;A&amp;lt;T&amp;gt;.B&lt;/SPAN&gt;, then that should call &lt;SPAN class=code&gt;A&amp;lt;T&amp;gt;.B.M&lt;/SPAN&gt;, and it should print out whatever the current value of &lt;SPAN class=code&gt;T&lt;/SPAN&gt; is -- in this case, "String". If the base class of &lt;SPAN class=code&gt;C&lt;/SPAN&gt; is &lt;SPAN class=code&gt;A&amp;lt;int&amp;gt;.B&lt;/SPAN&gt;, then that should call &lt;SPAN class=code&gt;A&amp;lt;int&amp;gt;.B.M&lt;/SPAN&gt;, so it should print out "Int32".&lt;/P&gt;
&lt;P minmax_bound="true"&gt;We choose the latter as the base class. That was certainly a surprise to me. And Stuart Ballard. And, amusingly enough, when I sprang this one upon Anders and didn't give him time to think about it carefully, it was a surprise to him as well. When&amp;nbsp;I sprang it on Cyrus, he&amp;nbsp;cheerfully pointed out that he already posted &lt;A class="" href="http://blogs.msdn.com/cyrusn/archive/2005/08/01/446431.aspx" mce_href="http://blogs.msdn.com/cyrusn/archive/2005/08/01/446431.aspx"&gt;a harder version of this problem back in 2005&lt;/A&gt;, the solution of which Stuart characterized back then as "Insanely complex, but it makes perfect sense." I couldn't agree more, though at least my version of the puzzle is somewhat simpler.&lt;/P&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;Anyway, why on earth ought that to be the case? Surely the &lt;SPAN class=code&gt;B&lt;/SPAN&gt; in &lt;SPAN class=code&gt;class C : B&lt;/SPAN&gt; means the immediately containing class, which is &lt;SPAN class=code&gt;A&amp;lt;T&amp;gt;.B&lt;/SPAN&gt;, not &lt;SPAN class=code&gt;A&amp;lt;int&amp;gt;.B&lt;/SPAN&gt;! And yet it does not.&lt;/P&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;These generics are screwing up our intuitions. Let's look at an example which has no generics at all:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;public class D {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public class E {}&lt;BR&gt;}&lt;BR&gt;public class F {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public class E { }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public class G {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public E e; // clearly F.E &lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;}&lt;BR&gt;public class H : D {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public E e; // clearly D.E&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;This is all legal so far, and should be pretty clear. When we are binding a name to a type, the&amp;nbsp;type we get is allowed to be &lt;EM&gt;a member&amp;nbsp;of any base class&lt;/EM&gt; &lt;STRONG&gt;&lt;EM&gt;or&lt;/EM&gt;&lt;/STRONG&gt; &lt;EM&gt;a member of any outer class&lt;/EM&gt;. But what if we have &lt;EM&gt;both&lt;/EM&gt; to choose from?&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;public class J {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public class E {}&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public class K : D {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public E e; // Is this J.E or D.E?&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;We could just throw up our hands and say that this is ambiguous and therefore illegal, but we'd rather not do that if we can avoid it. We have to prefer one of them, and &lt;STRONG&gt;we've decided that we will give priority to base classes over outer classes&lt;/STRONG&gt;. Derived classes have an "is a kind of" relationship with their base classes, and that is logically a "tighter" binding than the "is contained in" relationship that inner classes have with outer classes.&lt;/P&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;Another way to think about it is that all the members you get from your base class are all "in the current scope"; therefore all the members you get from outer scopes&amp;nbsp;are given lower priority, since &lt;EM&gt;stuff inside inner scopes takes priority over stuff in outer scopes&lt;/EM&gt;.&lt;/P&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;The algorithm we use to search for a name used in the context of a type S is as follows:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;
&lt;DIV minmax_bound="true" mce_keep="true"&gt;search S's type parameters&lt;/DIV&gt;&lt;/LI&gt;
&lt;LI&gt;
&lt;DIV minmax_bound="true" mce_keep="true"&gt;search S's accessible inner classes&lt;/DIV&gt;&lt;/LI&gt;
&lt;LI&gt;
&lt;DIV minmax_bound="true" mce_keep="true"&gt;search accessible inner classes of all of S's base classes, going in order from most to least derived&lt;/DIV&gt;&lt;/LI&gt;
&lt;LI&gt;
&lt;DIV minmax_bound="true" mce_keep="true"&gt;S←S's outer class, start over&lt;/DIV&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;(And if that fails then we invoke the whole mechanism of searching the namespaces that are in scope, checking alias clauses, etc.)&lt;/P&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;With that in mind, now&amp;nbsp;the solution&amp;nbsp;should finally&amp;nbsp;make some sense. At the point where we are resolving the base class of &lt;SPAN class=code&gt;C&lt;/SPAN&gt; we know that &lt;SPAN class=code&gt;C&lt;/SPAN&gt; has no type parameters. We do not know what the base class or inner classes of &lt;SPAN class=code&gt;C&lt;/SPAN&gt; are -- that's what we're trying to figure out -- so we skip checking them.&lt;/P&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;The next thing we check is the outer class, which is &lt;SPAN class=code&gt;A&amp;lt;T&amp;gt;.B&lt;/SPAN&gt;, but we do NOT say, aha, the outer class is called &lt;SPAN class=code&gt;B&lt;/SPAN&gt;, we're done. That is not at all what the algorithm above says. Instead, it says check &lt;SPAN class=code&gt;A&amp;lt;T&amp;gt;.B&lt;/SPAN&gt; to see if it has a type variable called &lt;SPAN class=code&gt;B&lt;/SPAN&gt; or an inner type called &lt;SPAN class=code&gt;B&lt;/SPAN&gt;. It does not, so we keep searching.&lt;/P&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;The base type of &lt;SPAN class=code&gt;A&amp;lt;T&amp;gt;.B&lt;/SPAN&gt; is &lt;SPAN class=code&gt;A&amp;lt;int&amp;gt;&lt;/SPAN&gt;. The outer type of &lt;SPAN class=code&gt;A&amp;lt;T&amp;gt;.B&lt;/SPAN&gt; is &lt;SPAN class=code&gt;A&amp;lt;T&amp;gt;&lt;/SPAN&gt;. Both have an accessible inner class called &lt;SPAN class=code&gt;B&lt;/SPAN&gt;. Which do we pick?&amp;nbsp;&lt;STRONG&gt;The base type gets searched first&lt;/STRONG&gt;, so &lt;SPAN class=code&gt;B&lt;/SPAN&gt; resolves to &lt;SPAN class=code&gt;A&amp;lt;int&amp;gt;.B&lt;/SPAN&gt;. Obviously.&lt;/P&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;Having&amp;nbsp;members of base classes&amp;nbsp;bind tighter than members from outer scopes&amp;nbsp;can lead to&amp;nbsp;bizarre situations but they are generally pretty contrived. For example:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;public class K { public class L {} }&lt;BR&gt;public class L&amp;nbsp;:&amp;nbsp;K&amp;nbsp;{ &lt;BR&gt;&amp;nbsp; L myL; // this is K.L!&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;And of course,&amp;nbsp;you&amp;nbsp;can always get around these problems by eliminating the ambiguity:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P minmax_bound="true"&gt;public class&amp;nbsp;A&amp;lt;T&amp;gt;&amp;nbsp;{&lt;BR&gt;&amp;nbsp; public class&amp;nbsp;B : A&amp;lt;int&amp;gt;&amp;nbsp;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;public void M() { ... }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public class C : A&amp;lt;T&amp;gt;.B { } // no longer ambiguous which B is picked.&lt;/P&gt;&lt;/SPAN&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;Finally, why did I say that you couldn't appeal to the standard? When I wrote that I actually thought that the standard was wrong, but upon a closer reading, I see that it is correct. It's just really hard to read:&lt;/P&gt;&lt;SPAN class=spec&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;Otherwise, if T contains a nested accessible type having name I and K type parameters, then the namespace-or-type-name refers to that type constructed with the given type arguments. If there is more than one such type, the type declared within the more derived type is selected.&lt;/P&gt;&lt;/SPAN&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;By &lt;SPAN class=spec&gt;"if T contains a nested accessible type"&lt;/SPAN&gt;, it means "if T, &lt;EM&gt;or any of its base classes&lt;/EM&gt;, contains a nested accessible type". I completely failed to comprehend that&amp;nbsp;the first n times I read that section. I'll see if I can get that clarified in the next version of the standard.&lt;/P&gt;
&lt;P minmax_bound="true" mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=4089673" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category></item><item><title>An Inheritance Puzzle, Part One</title><link>http://blogs.msdn.com/ericlippert/archive/2007/07/27/an-inheritance-puzzle-part-one.aspx</link><pubDate>Fri, 27 Jul 2007 19:36:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:4083090</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>24</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/4083090.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=4083090</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;Once more I have returned from my ancestral homeland, after some weeks of sun, rain, storms, wind, calm, friends and family. I could certainly use another few weeks, but it is good to be back too.&lt;/P&gt;
&lt;P&gt;Well, enough chit-chat; back to programming language design. Here's an interesting combination of subclassing with nesting. Before trying it, what do you think this program &lt;EM&gt;should&lt;/EM&gt; output?&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;public class A&amp;lt;T&amp;gt; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public class B : A&amp;lt;&lt;STRONG&gt;int&lt;/STRONG&gt;&amp;gt; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void M() {&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; System.Console.WriteLine(typeof(T).ToString());&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; public class C : B { }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;}&lt;BR&gt;class MainClass {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; static void Main() {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; A&amp;lt;&lt;STRONG&gt;string&lt;/STRONG&gt;&amp;gt;.B.C c = new A&amp;lt;&lt;STRONG&gt;string&lt;/STRONG&gt;&amp;gt;.B.C();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c.M();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;Should this say that T is int, string or&amp;nbsp;something else?&amp;nbsp;Or should this program not compile in the first place?&lt;/P&gt;
&lt;P&gt;It turned out that&amp;nbsp;the actual&amp;nbsp;result is not what &lt;EM&gt;I&lt;/EM&gt; was expecting at least.&amp;nbsp;I learn something new about this language every day.&lt;/P&gt;
&lt;P&gt;Can you justify either the actual behaviour or what you believe the behaviour should be? Note that appealing to the C# standard will not help you here because the standard gets it wrong.&lt;/P&gt;
&lt;P&gt;I'll discuss how exactly the standard gets it wrong and what the justification is for the actual behaviour next time on FAIC.&lt;/P&gt;
&lt;P&gt;[UPDATE: I have reviewed the standard more carefully. The standard is actually correct, but really hard to read. I'll post a full analysis on Monday.]&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=4083090" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category></item><item><title>Even More Conversion Trivia, Part Two</title><link>http://blogs.msdn.com/ericlippert/archive/2007/05/01/even-more-conversion-trivia-part-two.aspx</link><pubDate>Tue, 01 May 2007 17:24:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:2358328</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/2358328.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=2358328</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;Reader Barry Kelly came up with the solution I was thinking of for my trivia question yesterday. If the value in question is, say, a nullable integer which has no value then casting it explicitly to object results in the null object. Calling a virtual method on a null object results in an exception at runtime. However, using it implicitly as an object boxes up the nullable int as a valid &lt;SPAN class=code&gt;ValueType&lt;/SPAN&gt;, which overrides &lt;SPAN class=code&gt;ToString&lt;/SPAN&gt;. So that's the difference: the one without the cast produces an empty string, the one with the cast throws an exception.&lt;/P&gt;
&lt;P&gt;Honourable mention to reader Bill Wagner, who points out that if the object implements an interface with a &lt;SPAN class=code&gt;ToString&lt;/SPAN&gt; method then there are two &lt;SPAN class=code&gt;ToString&lt;/SPAN&gt; slots, one from the base class and one from the interface. Casting to &lt;SPAN class=code&gt;object&lt;/SPAN&gt; can cause overload resolution to pick the base version over the interface version, which might otherwise be preferred. (This reminds me of another fun fact about C# overload resolution which I will blog about at a later date.)&lt;/P&gt;
&lt;P&gt;As Barry Kelly points out, the CLR took a design change with Visual Studio 2005 Beta 2 to implement the special case that a nullable without a value becomes a null &lt;SPAN class=code&gt;ValueType&lt;/SPAN&gt; rather than a boxed &lt;SPAN class=code&gt;ValueType&lt;/SPAN&gt; when boxed. How then do we implement the desired behaviour, ie, that calling &lt;SPAN class=code&gt;ToString&lt;/SPAN&gt; without a cast creates a boxed &lt;SPAN class=code&gt;ValueType&lt;/SPAN&gt; regardless of whether the nullable has a value?&lt;/P&gt;
&lt;P&gt;Fortunately the CLR implemented a special kind of virtual call, called the "constrained" virtual call. Without the ability to constrain the transformation of a value to a particular type when making a virtual call, certain operations become difficult to codegen. (In particular, it is hard to do virtual calls on type parameters of generic types, because you might not know whether the type parameter is going to be a value type or a reference type under construction.) If you take a look at the IL we generate for something like &lt;SPAN class=code&gt;foo.ToString()&lt;/SPAN&gt; on a nullable int, it looks like:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;ldsflda&amp;nbsp;&amp;nbsp;&amp;nbsp; valuetype [mscorlib]System.Nullable`1&amp;lt;int32&amp;gt; Test::foo&lt;BR&gt;constrained. valuetype [mscorlib]System.Nullable`1&amp;lt;int32&amp;gt;&lt;BR&gt;callvirt&amp;nbsp;&amp;nbsp; instance string [mscorlib]System.Object::ToString()&lt;/P&gt;&lt;/SPAN&gt;
&lt;P mce_keep="true"&gt;Which tells the CLR to box up that thing as is, rather than doing a boxing operation. Had we inserted a cast in there we would have generated&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P mce_keep="true"&gt;ldsfld&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; valuetype [mscorlib]System.Nullable`1&amp;lt;int32&amp;gt; Test::foo&lt;BR&gt;box&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; valuetype [mscorlib]System.Nullable`1&amp;lt;int32&amp;gt;&lt;BR&gt;callvirt&amp;nbsp;&amp;nbsp; instance string [mscorlib]System.Object::ToString()&lt;/P&gt;&lt;/SPAN&gt;
&lt;P mce_keep="true"&gt;instead.&lt;BR&gt;&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=2358328" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category></item><item><title>Even More Conversion Trivia</title><link>http://blogs.msdn.com/ericlippert/archive/2007/04/30/even-more-conversion-trivia.aspx</link><pubDate>Tue, 01 May 2007 00:10:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:2344327</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>14</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/2344327.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=2344327</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;I learn something new about C# every day. This is a subtle and tricky language.&lt;/P&gt;
&lt;P&gt;Pop quiz: &lt;SPAN class=code&gt;foo&lt;/SPAN&gt; is of a type which has a base class which has made a normal, everyday virtual override of &lt;SPAN class=code&gt;System.Object.ToString&lt;/SPAN&gt;. There are no additional overrides, hides, etc&amp;nbsp;of &lt;SPAN class=code&gt;ToString&lt;/SPAN&gt; anywhere in &lt;SPAN class=code&gt;foo&lt;/SPAN&gt;'s inheritance hierarchy. No ToString extension methods, etc. Under what circumstances do &lt;SPAN class=code&gt;foo.ToString()&lt;/SPAN&gt; and &lt;SPAN class=code&gt;((object)foo).ToString()&lt;/SPAN&gt; produce different results? Remember, it is a virtual function, so the cast should not make a difference in what function is actually called.&lt;/P&gt;
&lt;P&gt;As it turns out, my mistaken belief that the two of these have the same semantics caused a bug in the part of the compiler where we translate an expression tree lambda into a call to the &lt;SPAN class=code&gt;Lambda&amp;lt;T&amp;gt;&lt;/SPAN&gt; factory. That in turn was masking an even more subtle bug in the dynamic expression tree compiler.&lt;/P&gt;
&lt;P&gt;Anyone out there have a guess as to what type and value of &lt;SPAN class=code&gt;foo&lt;/SPAN&gt; produces different behaviour here? I'll post the answer next time along with some discussion of the codegen issue.&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=2344327" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Puzzles/default.aspx">Puzzles</category></item></channel></rss>