<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>Jon Skeet: Coding Blog</title><link>http://msmvps.com/blogs/jon_skeet/default.aspx</link><description>C#, .NET, Java, software development etc
**This is my personal blog. The views expressed on these pages are mine alone and not those of my employer.**</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/JonSkeetCodingBlog" /><feedburner:info uri="jonskeetcodingblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><title>Book Review: Async in C# 5.0</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/2WGaSufZ7Og/book-review-async-in-c-5-0.aspx</link><pubDate>Mon, 20 May 2013 23:14:02 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1830869</guid><dc:creator>skeet</dc:creator><slash:comments>3</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1830869</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1830869</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2013/05/21/book-review-async-in-c-5-0.aspx#comments</comments><description>&lt;p&gt;Resources:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://www.amazon.com/Async-C-5-0-Alex-Davies/dp/1449337163"&gt;Amazon&lt;/a&gt;, &lt;a href="http://www.barnesandnoble.com/w/async-in-c-5-0-alex-davies/1112412817?ean=9781449337162"&gt;Barnes and Noble&lt;/a&gt;, &lt;a href="https://play.google.com/store/books/details/Alex_Davies_Async_in_C_5_0?id=xT45qhFrVnUC&amp;amp;feature=search_result#?t=W251bGwsMSwyLDEsImJvb2steFQ0NXFoRnJWblVDIl0."&gt;Play Books&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://shop.oreilly.com/product/0636920026532.do"&gt;The book&amp;#39;s web site&lt;/a&gt; (O&amp;#39;Reilly) – downloads, errata etc &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;A while ago I was attending one of the &lt;a href="http://www.developerdeveloperdeveloper.com/home/"&gt;Developer, Developer, Developer&lt;/a&gt; conference in Reading, and I heard Alex Davies give a talk about actors and async. He mentioned that he was in the process of writing a short book for O&amp;#39;Reilly about async in C# 5, and I offered to review it for him. Many months later (sorry Alex!) I&amp;#39;m finally getting round to it.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Disclaimer: &lt;/strong&gt;The review copy was given to me for free, and equally the book is arguably a competitor of the upcoming 3rd edition of C# in Depth from the view of readers who already own the 2nd edition... so you could say I&amp;#39;m biased in both directions. Hopefully they cancel out.&lt;/p&gt;  &lt;p&gt;This is a book purely on async. It&amp;#39;s not a general C# book, and it doesn&amp;#39;t even cover the tiny non-async features in C# 5. It&amp;#39;s &lt;em&gt;all&lt;/em&gt; about asynchrony. As you&amp;#39;d expect, it&amp;#39;s therefore pretty short (92 pages) and can comfortably be consumed in a single session. Alex&amp;#39;s writing style is informal and easy to read. Of course the &lt;em&gt;topic&lt;/em&gt; of the book is anything but simple, so even though you may read the whole book in one go first time, that doesn&amp;#39;t mean you&amp;#39;re likely to fully internalize it straight away. The book is divided into 15 short chapters, so you can revisit specific areas as and when you need to.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;strong&gt;Aside&lt;/strong&gt;&lt;/p&gt;    &lt;p&gt;I&amp;#39;ve been writing and speaking about async for about two and a half years now. I&amp;#39;ve tried various ways of explaining it, and I&amp;#39;m pretty sure it&amp;#39;s one of those awkward concepts which really just needs to click eventually. I&amp;#39;ve had some mails from people for whom my explanation was the one to do the trick... and other mails from folks who only &amp;quot;got it&amp;quot; after seeing another perspective. I&amp;#39;d encourage anyone learning about async to read a variety of books, articles, blog posts and so on. I don&amp;#39;t even think it&amp;#39;s a matter of finding the single &amp;quot;right&amp;quot; explanation for you – it&amp;#39;s a matter of letting them all percolate.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The book covers all the topics you&amp;#39;d expect it to:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Why asynchrony is important &lt;/li&gt;    &lt;li&gt;Drawbacks of library-only approaches &lt;/li&gt;    &lt;li&gt;How async/await behaves in general &lt;/li&gt;    &lt;li&gt;Threading and synchronization contexts &lt;/li&gt;    &lt;li&gt;Exceptions &lt;/li&gt;    &lt;li&gt;Different code contexts (ASP.NET, WinRT, regular UI apps) &lt;/li&gt;    &lt;li&gt;How async code is compiled &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Additionally there are brief sections on unit testing, parallelism and actors. Personally I&amp;#39;d have preferred the actors part to be omitted, with more discussion on the testing side – particularly in terms of how to write deterministic asynchronous tests. However, I know that Alex is a big fan of actors, so I can forgive a little self-indulgence on that front.&lt;/p&gt;  &lt;p&gt;There&amp;#39;s one area where I&amp;#39;m not sure I agree with the advice in the book: exceptions. Alex repeatedly gives the advice that you shouldn&amp;#39;t let exceptions go unobserved. I used to go along with that almost without thinking – but now I&amp;#39;m not so sure. There are definitely cases where that definitely &lt;em&gt;is&lt;/em&gt; the case, but I&amp;#39;m not as comfortable with the global advice as I used to be. I&amp;#39;ll try to put my thoughts in order on this front and blog about this separately at a later date.&lt;/p&gt;  &lt;p&gt;That aside, this is a good, pragmatic book. To be honest, I suspect no book on async is going to go into quite as many details as &lt;a href="http://blogs.msdn.com/b/pfxteam/"&gt;the PFX team blog&lt;/a&gt;, and that&amp;#39;s probably a good thing. But &amp;quot;Async in C# 5.0&amp;quot; is a very good starting point for anyone wanting to get to grips with async, and I in no way begrudge any potential C# in Depth 3rd edition sales I may lose by saying so ;)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1830869" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/2WGaSufZ7Og" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Books/default.aspx">Books</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Book+reviews/default.aspx">Book reviews</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2013/05/21/book-review-async-in-c-5-0.aspx</feedburner:origLink></item><item><title>New tool to play with: SemanticMerge</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/vL8hINxgSKI/new-tool-to-play-with-semanticmerge.aspx</link><pubDate>Thu, 18 Apr 2013 21:38:23 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1827732</guid><dc:creator>skeet</dc:creator><slash:comments>3</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1827732</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1827732</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2013/04/18/new-tool-to-play-with-semanticmerge.aspx#comments</comments><description>&lt;p&gt;A little while ago I was contacted about a new merge tool from the company behind &lt;a href="http://www.plasticscm.com/"&gt;PlasticSCM&lt;/a&gt;. (I haven&amp;#39;t used Plastic myself, but I&amp;#39;d heard of it.) My initial reaction was that I wasn&amp;#39;t interested in anything which required me to learn yet another source control system, but SemanticMerge is independent of PlasticSCM.&lt;/p&gt;  &lt;p&gt;My interested was piqued when I learned that SemanticMerge is actually built on &lt;a href="http://en.wikipedia.org/wiki/Microsoft_Roslyn"&gt;Roslyn&lt;/a&gt;. I don&amp;#39;t generally care much about implementation details, but I&amp;#39;m looking out for uses of Roslyn outside Microsoft, partly to see if I can gain any inspiration for using it myself. Between the name and the implementation detail, it should be fairly obvious that this is a tool which understands changes in C# source code rather better than a plain text diff.&lt;/p&gt;  &lt;p&gt;I&amp;#39;ve had SemanticMerge installed on one of my laptops for a month or so now. Unfortunately it&amp;#39;s getting pretty light use – my main coding outside work is on &lt;a href="http://noda-time.googlecode.com"&gt;Noda Time&lt;/a&gt;, and as I perform the vast majority of the commits, the only time I really need to perform merges is when I&amp;#39;ve forgotten to push a commit from one machine before switching to another. I&amp;#39;ve used it for diffs though, and it seems to be doing the right thing there – showing which members have been added, moved, changed etc.&lt;/p&gt;  &lt;p&gt;I don&amp;#39;t believe it can currently support multi-file changes – for example, spotting that a lot of changes are all due to a rename operation – but even if it doesn&amp;#39;t right now, I suspect that may be worked on in the future. And of course, the merge functionality is the main point.&lt;/p&gt;  &lt;p&gt;SemanticMerge is now in beta, so &lt;a href="http://semanticmerge.com/"&gt;pop over to the web site&lt;/a&gt; and give it a try.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1827732" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/vL8hINxgSKI" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/General/default.aspx">General</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2013/04/18/new-tool-to-play-with-semanticmerge.aspx</feedburner:origLink></item><item><title>The Open-Closed Principle, in review</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/uPCzYxuuzoI/the-open-closed-principle-in-review.aspx</link><pubDate>Fri, 15 Mar 2013 09:22:01 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1825236</guid><dc:creator>skeet</dc:creator><slash:comments>32</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1825236</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1825236</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2013/03/15/the-open-closed-principle-in-review.aspx#comments</comments><description>&lt;h2&gt;Background&lt;/h2&gt;  &lt;p&gt;I&amp;#39;ve been to a few talks on &lt;a href="http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)"&gt;SOLID&lt;/a&gt; before. Most of the principles seem pretty reasonable to me – but I&amp;#39;ve never &amp;quot;got&amp;quot; the open-closed principle (OCP from here on). At CodeMash this year, I mentioned this to the wonderful &lt;a href="http://truncatedcodr.wordpress.com/"&gt;Cori Drew&lt;/a&gt;, who said that she&amp;#39;d been at a user group talk where she felt it was explained well. She mailed me a link to the &lt;a href="http://usergroup.tv/videos/how-to-code-design-patterns"&gt;user group video&lt;/a&gt;, which I &lt;em&gt;finally&lt;/em&gt; managed to get round to watching last week. (The OCP part is at around 1 hour 20.)&lt;/p&gt;  &lt;p&gt;Unfortunately I still wasn&amp;#39;t satisfied, so I thought I&amp;#39;d try to hit up the relevant literature. Obviously there are umpteen guides to OCP, but I decided to start with Wikipedia, and go from there. I mentioned my continuing disappointment on Twitter, and the conversation got lively. Uncle Bob Martin (one of the two &amp;quot;canonical sources&amp;quot; for OCP) wrote a follow-up blog post, and I decided it would be worth writing one of my own, too, which you&amp;#39;re now reading.&lt;/p&gt;  &lt;p&gt;I should say up-front that in some senses this blog post isn&amp;#39;t so much about the details of the open-closed principle, as about the importance of careful choice of terminology at all levels. As we&amp;#39;ll see later, when it comes to the &amp;quot;true&amp;quot; meaning of OCP, I&amp;#39;m pretty much with Uncle Bob: it&amp;#39;s motherhood and apple pie. But I believe that meaning is much more clearly stated in various other principles, and that OCP as the expression of an idea is doing more harm than good.&lt;/p&gt;  &lt;h2&gt;Reading material&lt;/h2&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;Wikipedia OCP entry&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.objectmentor.com/resources/articles/ocp.pdf"&gt;Uncle Bob Martin&amp;#39;s 1996 paper&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://codecourse.sourceforge.net/materials/The-Importance-of-Being-Closed.pdf"&gt;Craig Larman&amp;#39;s comparison with Protected Variation&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blog.8thlight.com/uncle-bob/2013/03/08/AnOpenAndClosedCase.html"&gt;Uncle Bob&amp;#39;s blog response&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;h2&gt;So what is it? (Part 1 – high level)&lt;/h2&gt;  &lt;p&gt;This is where it gets interesting. You see, there appear to be several different interpretation of the principle – some only subtly distinct, others seemingly almost unrelated. Even without looking anything up, I knew an expanded version of the name:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Modules should be open for extension and closed for modification.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The version quoted in Wikipedia and in Uncle Bob&amp;#39;s paper actually uses &amp;quot;Software entities (classes, modules, functions, etc.)&amp;quot; instead of modules, but I&amp;#39;m not sure that really helps. Now I&amp;#39;m not naïve enough to expect everything in a principle to be clear just from the title, but I do expect &lt;em&gt;some&lt;/em&gt; light to be shed. In this case, unfortunately I&amp;#39;m none the wiser. &amp;quot;Open&amp;quot; and &amp;quot;closed&amp;quot; sound permissive and restrictive respectively, but without very concrete ideas about what &amp;quot;extension&amp;quot; and &amp;quot;modification&amp;quot; mean, it&amp;#39;s hard to tell much more.&lt;/p&gt;  &lt;p&gt;Fair enough – so we read on to the next level. Unfortunately I don&amp;#39;t have Bertrand Meyer&amp;#39;s &amp;quot;Object-Oriented Software Construction&amp;quot; book (which I take to be the original), but Uncle Bob&amp;#39;s paper is freely available. Wikipedia&amp;#39;s summary of Meyer&amp;#39;s version is:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The idea was that once completed, the implementation of a class could only be modified to correct errors; new or changed features would require that a different class be created. That class could reuse coding from the original class through inheritance. The derived subclass might or might not have the same interface as the original class.&lt;/p&gt;    &lt;p&gt;Meyer&amp;#39;s definition advocates implementation inheritance. Implementation can be reused through inheritance but interface specifications need not be. The existing implementation is closed to modifications, and new implementations need not implement the existing interface.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;And Uncle Bob&amp;#39;s high level description is:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Modules that conform to the open-closed principle have two primary attributes.&lt;/p&gt;    &lt;ol&gt;     &lt;li&gt;They are &amp;quot;Open For Extension&amp;quot;. This means that the behavior of the module can be extended. That we can make the module behave in new and different ways as the requirements of the application change, or to meet the needs of new applications. &lt;/li&gt;      &lt;li&gt;They are &amp;quot;Closed for Modiﬁcation&amp;quot;. The source code of such a module is inviolate. No one is allowed to make source code changes to it. &lt;/li&gt;   &lt;/ol&gt; &lt;/blockquote&gt;  &lt;p&gt;I immediately took a dislike to both of these descriptions. Both of them specifically say that the source code can&amp;#39;t be changed, and the description of Meyer&amp;#39;s approach to &amp;quot;make a change by extending a class&amp;quot; feels like a ghastly abuse of inheritance to me... and goes firmly against my (continued) belief in Josh Bloch&amp;#39;s advice of &amp;quot;design for inheritance or prohibit it&amp;quot; – where in the majority of cases, designing a &lt;em&gt;class&lt;/em&gt; for inheritance involves an awful lot of work for little gain. Designing an &lt;em&gt;interface&lt;/em&gt; (or pure abstract class) still involves work, but with fewer restrictions and risks.&lt;/p&gt;  &lt;p&gt;Craig Larman&amp;#39;s article uses the term &amp;quot;closed&amp;quot; in a &lt;em&gt;much&lt;/em&gt; more reasonable way, to my mind:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Also, the phrase &amp;quot;closed with respect to X&amp;quot; means that clients are not affected if X changes.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;When I say &amp;quot;more reasonable way&amp;quot; I mean in terms of how I want to write code... not in terms of the use of the word &amp;quot;closed&amp;quot;. This is simply not how the word &amp;quot;closed&amp;quot; is used elsewhere in my experience. In the rare cases where &amp;quot;closed&amp;quot; &lt;em&gt;is&lt;/em&gt; used with &amp;quot;to&amp;quot;, it&amp;#39;s usually in terms of what&amp;#39;s not allowed in: &amp;quot;This bar is closed to under 18s&amp;quot; for example. Indeed, that&amp;#39;s how I read &amp;quot;closed to modification&amp;quot; and that appears to be backed up by the two quotes which say that once a class is complete, the source code cannot be changed.&lt;/p&gt;  &lt;p&gt;Likewise the meaning of &amp;quot;open for extension&amp;quot; seems unusual to me. I&amp;#39;d argue that the intuitive meaning is &amp;quot;can be extended&amp;quot; – where the use of the term &amp;quot;extended&amp;quot; certainly nods towards inheritance, even if it&amp;#39;s not intended meaning. If the idea is &amp;quot;we can make the module behave differently&amp;quot; – as Uncle Bob&amp;#39;s description suggests – then &amp;quot;open for extension&amp;quot; is a very odd way of expressing that idea. I&amp;#39;d even argue that in the example given later, it&amp;#39;s not the &amp;quot;open&amp;quot; module that behaves differently – it&amp;#39;s the &lt;em&gt;combination&lt;/em&gt; of the module and its collaborators, acting as a unified program, which behaves differently after some aspects are modified.&lt;/p&gt;  &lt;h2&gt;So what is it? (Part 2 – more detail)&lt;/h2&gt;  &lt;p&gt;Reading on through the rest of Uncle Bob&amp;#39;s paper, the ideas become much more familiar. There&amp;#39;s a reasonable example of a function which is asked to draw a collection of shapes: the bad code is aware of all the types of shape available, and handles each one separately. The good code uses an abstraction where each shape (Circle, Square) knows how to draw itself and inherits from a common base class (Shape). Great stuff... but what&amp;#39;s that got to do with what was described above? How are the concepts of &amp;quot;open&amp;quot; and &amp;quot;closed&amp;quot; clarified?&lt;/p&gt;  &lt;p&gt;The answer is that they&amp;#39;re not. The word &amp;quot;open&amp;quot; doesn&amp;#39;t occur anywhere in the rest of the text, other than as part of the term &amp;quot;open-closed principle&amp;quot; or as a label for &amp;quot;open client&amp;quot;. While it&amp;#39;s perhaps rather easier to see this in hindsight, I suspect that any time a section which is meant to clarify a concept doesn&amp;#39;t use some of the key words used to describe the concept in a nutshell, that description should be treated as suspect.&lt;/p&gt;  &lt;p&gt;The word &amp;quot;closed&amp;quot; appears more often, but &lt;em&gt;only&lt;/em&gt; in terms of &amp;quot;closed against&amp;quot; which is never actually defined. (Is &amp;quot;closed against&amp;quot; the same as &amp;quot;closed for&amp;quot;?) Without Craig Larman&amp;#39;s explanation, sentences like this make little sense to me:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The function DrawAllShapes does not conform to the open-closed principle because it cannot be closed against new kinds of shapes.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Even Craig&amp;#39;s explanation feels somewhat at odds with Uncle Bob&amp;#39;s usage, as it talks about &lt;em&gt;clients&lt;/em&gt; being affected. This is another of the issues I have with the original two descriptions: they talk about a &lt;em&gt;single module&lt;/em&gt; being open/closed, whereas we&amp;#39;re dealing with abstractions where there are naturally at least two pieces of code involved (and usually three). Craig&amp;#39;s description of changes in one module not affecting clients is describing a &lt;em&gt;relationship&lt;/em&gt; – which is a far more useful way of approaching things. Even thinking about the shape example, I&amp;#39;m getting increasingly confused about exactly what&amp;#39;s open and what&amp;#39;s closed. It feels to me like it&amp;#39;s neither the concrete shape classes nor the shape-drawing code which is open or closed – it&amp;#39;s the interface between the two; the abstract Shape class. After all, these statements seem reasonable:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The Shape class is open for extension: there can be many different concrete subclasses, and code which only depends on the Shape class doesn&amp;#39;t need to know about them in order to use them when they are presented as shapes. &lt;/li&gt;    &lt;li&gt;The Shape class is closed for modification: no existing functions can be removed (as they may be relied on by existing clients) and no new pure virtual functions can be added (as they will not be implemented by existing subclasses). &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;It&amp;#39;s still not how I&amp;#39;d choose to express it, but at least it feels like it makes sense in very concrete terms. It doesn&amp;#39;t work well with how Uncle Bob uses the term &amp;quot;closed&amp;quot; though, so I still think I may be on a different page when it comes to that meaning. (Uncle Bob does also make the point that any significant program isn&amp;#39;t going to adhere to the principle completely in every part of the code – but in order to judge where it&amp;#39;s appropriate to be closed, I do really need to understand what being closed means.)&lt;/p&gt;  &lt;p&gt;Just to make it crystal clear, other than the use of the word &amp;quot;closed,&amp;quot; the low-level description of what&amp;#39;s good and what&amp;#39;s bad, and why, is absolutely fine. I really have no problems with it. As I said at the start, the idea being expressed makes perfect sense. It just doesn&amp;#39;t work (for me) when expressed in the terms used at a higher level.&lt;/p&gt;  &lt;h2&gt;Protected Variation&lt;/h2&gt;  &lt;p&gt;By contrast, let&amp;#39;s look at a closely related idea which I hadn&amp;#39;t actually heard about before I started all this research: protected variation. This name was apparently coined by Alistair Cockburn, and Craig Larman either quotes or paraphrases this as:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Identify points of predicted variation and create a stable interface around them.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now that&amp;#39;s a description I can immediately identify with. Every single word of it makes sense to me, even without reading any more of Craig&amp;#39;s article. (I &lt;em&gt;have&lt;/em&gt; read the rest, obviously, and I&amp;#39;d encourage others to do so.) This goes back to Josh Bloch&amp;#39;s &amp;quot;design for inheritance or prohibit it&amp;quot; motto: identifying points of predicted variation is hard, and it&amp;#39;s &lt;em&gt;necessary&lt;/em&gt; in order to create a stable interface which is neither too constrictive for implementations nor too woolly for clients. With class inheritance there&amp;#39;s the additional concern of interactions within a class hierarchy when a virtual method is called.&lt;/p&gt;  &lt;p&gt;So in Uncle Bob&amp;#39;s Shape example, &lt;em&gt;all&lt;/em&gt; there is is a point of predicted variation: how the shape is drawn. PV suggests the converse as well – that as well as points of predicted variation, there may be points which will &lt;em&gt;not&lt;/em&gt; vary. That&amp;#39;s inherent in the API to some extent – every shape must be capable of drawing itself with no further information (the Draw method has no parameters) but it could also be extended to non-virtual aspects. For example, we could decide that every shape has one (and only one) colour, which will not change during its lifetime. That can be implemented in the Shape class itself – with no predicted variation, there&amp;#39;s no need of polymorphism.&lt;/p&gt;  &lt;p&gt;Of course, the costs of incorrectly predicting variation can be high: if you predict more variation than is actually warranted, you waste effort on over-engineering. If you predict &lt;em&gt;less&lt;/em&gt; variation than is required, you usually end up &lt;em&gt;either&lt;/em&gt; having to change quite a lot of code (if it&amp;#39;s all under your control) &lt;em&gt;or&lt;/em&gt; having to come up with an &amp;quot;extended&amp;quot; interface. There&amp;#39;s the other aspect of shirking responsibility on this predicted variation to some extent, by making some parts &amp;quot;optional&amp;quot; – that&amp;#39;s like saying, &amp;quot;We know implementations will vary here in an incompatible way, but we&amp;#39;re not going to try to deal with it in the API. Good luck!&amp;quot; This usually arises in collection APIs, around mutating operations which may or may not be valid (based on whether the collection is mutable or not).&lt;/p&gt;  &lt;p&gt;Not only is PV easy to understand – it&amp;#39;s easy to remember for its comedy value, at least if you&amp;#39;re a fan of &lt;a href="http://en.wikipedia.org/wiki/The_Hitchhiker&amp;#39;s_Guide_to_the_Galaxy"&gt;The Hitchhiker&amp;#39;s Guide to the Galaxy&lt;/a&gt;. Remember Vroomfondel and Majikthise, the philosophers who invaded Cruxwan University just as Deep Thought was about to announce the answer to Life, the Universe, and Everything? Even though they were arguing with programmers, it sounds like they were actually the ones with software engineering experience:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&amp;quot;I&amp;#39;ll tell you what the problem is mate,&amp;quot; said Majikthise, &amp;quot;demarcation, that&amp;#39;s the problem!&amp;quot;&lt;/p&gt;    &lt;p&gt;[...]&lt;/p&gt;    &lt;p&gt;&amp;quot;That&amp;#39;s right!&amp;quot; shouted Vroomfondel, &amp;quot;we demand rigidly defined areas of doubt and uncertainty!&amp;quot;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;That sounds like a pretty good alternative description of Protected Variation to me.&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;So, that&amp;#39;s what I don&amp;#39;t like about OCP. The name, and the broad description – both of which I believe to be unhelpful, and poorly understood. (While I&amp;#39;ve obviously considered the possibility that I&amp;#39;m the only one who finds it confusing, I&amp;#39;ve heard enough variation in the explanations of it to suggest that I&amp;#39;m really &lt;em&gt;not&lt;/em&gt; the only one.)&lt;/p&gt;  &lt;p&gt;That sounds like a triviality, but I think it&amp;#39;s rather important. I suspect that OCP has been at least mentioned in passing in thousands if not tends of thousands of user groups and conferences. The purpose of such gatherings is largely for communication of ideas – and when a sound idea is poorly expressed, an opportunity is wasted. I suspect that any time Uncle Bob has personally presented it in detail, the idea has sunk in appropriately – possibly after some initial confusion about the terminology. But what about all the misinterpretations and &amp;quot;glancing blows&amp;quot; where OCP is only mentioned as a good thing that clearly everyone wants to adhere to, with no explanation beyond the obscure ones described in part one above? How many times did they shed more confusion than light?&lt;/p&gt;  &lt;p&gt;I believe more people are familiar with Uncle Bob&amp;#39;s work on OCP than Bertrand Meyer&amp;#39;s. Further, I suspect that if Bertrand Meyer hadn&amp;#39;t already introduced the name and brief description, Uncle Bob may well have come up with far more descriptive ones himself, and the world would have been a better place. Fortunately, we do &lt;em&gt;have&lt;/em&gt; a better name and description for a concept which is at least very closely related. (I&amp;#39;m not going to claim PV and OCP are identical, but close enough for a lot of uses.)&lt;/p&gt;  &lt;p&gt;Ultimately, words matter – particularly when it comes to single sentence descriptions which act as soundbytes; shorthand for communicating a complex idea. It&amp;#39;s not about whether the more complex idea can be understood after carefully reading thorough explanations. It&amp;#39;s about whether the shorthand conveys the essence of the idea in a clear way. On that front, I believe the open-closed principle fails – which is why I&amp;#39;d love to see it retired in favour of more accessible ones.&lt;/p&gt;  &lt;h3&gt;Note for new readers&lt;/h3&gt;  &lt;p&gt;I suspect this post may end up being read more widely than most of my blog entries. If you&amp;#39;re going to leave a comment, please be aware that the CAPTCHA doesn&amp;#39;t work on Chrome. I&amp;#39;m &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2010/09/05/very-quick-interlude-i-know-that-captchas-aren-t-working-on-this-blog-if-you-re-using-chrome.aspx"&gt;aware of this&lt;/a&gt;, but can&amp;#39;t fix it myself. If you right-click on the broken image and select &amp;quot;open in new tab&amp;quot; you should get a working image. Apologies for the inconvenience.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1825236" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/uPCzYxuuzoI" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/General/default.aspx">General</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2013/03/15/the-open-closed-principle-in-review.aspx</feedburner:origLink></item><item><title>C# in Depth 3rd edition available for early access, plus a discount code…</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/mbJpzW_rB34/c-in-depth-3rd-edition-available-for-early-access-plus-a-discount-code.aspx</link><pubDate>Sat, 16 Feb 2013 14:31:54 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1823884</guid><dc:creator>skeet</dc:creator><slash:comments>9</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1823884</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1823884</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2013/02/16/c-in-depth-3rd-edition-available-for-early-access-plus-a-discount-code.aspx#comments</comments><description>&lt;p&gt;Readers who follow me on Twitter or Google+ know this already, but…&lt;/p&gt;  &lt;p&gt;The third edition of C# in Depth is now available for early access from &lt;a href="http://www.manning.com/skeet3/"&gt;its page on the Manning website&lt;/a&gt;. I’ve been given a special discount code which expires at midnight EST on February 17th, so be quick if you want to use it – it gives 50% off either version. The code is “csharpsk”.&lt;/p&gt;  &lt;p&gt;It’s likely that we’ll have a separate (permanent) discount for readers who already own the second edition, but the details of that haven’t been decided yet.&lt;/p&gt;  &lt;p&gt;Just to be clear, the third edition is &lt;em&gt;largely &lt;/em&gt;the second edition plus the changes to cover C# 5 – I haven’t done as much rewriting as I did for the second edition, mostly because I was already pretty happy with the second edition :) Obviously the largest (by far) feature in C# 5 is async/await, which is covered in detail in the new chapter 15.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1823884" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/mbJpzW_rB34" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Books/default.aspx">Books</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2013/02/16/c-in-depth-3rd-edition-available-for-early-access-plus-a-discount-code.aspx</feedburner:origLink></item><item><title>Fun with Object and Collection Initializers</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/24RyeQVpi8Y/fun-with-object-and-collection-initializers.aspx</link><pubDate>Thu, 14 Feb 2013 22:59:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1823825</guid><dc:creator>skeet</dc:creator><slash:comments>10</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1823825</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1823825</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2013/02/14/fun-with-object-and-collection-initializers.aspx#comments</comments><description>&lt;p&gt;Gosh it feels like a long time since I’ve blogged – particularly since I’ve blogged anything really C#-language-related.&lt;/p&gt;  &lt;p&gt;At some point I want to blog about my two CodeMash 2013 sessions (making the C# compiler/team cry, and learning lessons about API design from the Spice Girls) but those will take significant time – so here’s a quick post about object and collection initializers instead. Two interesting little oddities...&lt;/p&gt;  &lt;h1&gt;Is it an object initializer? Is it a collection initializer? No, it’s a syntax error!&lt;/h1&gt;  &lt;p&gt;The first part came out of a real life situation – &lt;a href="https://code.google.com/p/noda-time/source/browse/src/NodaTime.Testing/TimeZones/FakeDateTimeZoneSource.cs"&gt;FakeDateTimeZoneSource&lt;/a&gt;, if you want to look at the complete context.&lt;/p&gt;  &lt;p&gt;Basically, I have a class designed to help test time zone-sensitive code. As ever, I like to create immutable objects, so I have a builder class. That builder class has various properties which we’d like to be able to set, and we’d also like to be able to provide it with the time zones it supports, as simply as possible. For the zones-only use case (where the other properties can just be defaulted) I want to support code like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; source = &lt;span class="Keyword"&gt;new&lt;/span&gt; FakeDateTimeZoneSource.Builder    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; CreateZone(&lt;span class="String"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;),    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; CreateZone(&lt;span class="String"&gt;&amp;quot;y&amp;quot;&lt;/span&gt;),    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; CreateZone(&lt;span class="String"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;),    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; CreateZone(&lt;span class="String"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;)    &lt;br /&gt;}.Build(); &lt;/div&gt;  &lt;p&gt;(&lt;code&gt;CreateZone&lt;/code&gt; is just a method to create an arbitrary time zone with the given name.)&lt;/p&gt;  &lt;p&gt;To achieve this, I made the &lt;code&gt;Builder&lt;/code&gt; implement &lt;code&gt;IEnumerable&amp;lt;DateTimeZone&amp;gt;&lt;/code&gt;, and created an &lt;code&gt;Add&lt;/code&gt; method. (In this case the &lt;code&gt;IEnumerable&amp;lt;&amp;gt;&lt;/code&gt; implementation actually works; in another case I&amp;#39;ve used explicit interface implementation and made the &lt;code&gt;GetEnumerator()&lt;/code&gt; method throw &lt;code&gt;NotSupportedException&lt;/code&gt;, as it&amp;#39;s really not &lt;em&gt;meant&lt;/em&gt; to be called in either case.)&lt;/p&gt;  &lt;p&gt;So far, so good. The collection initializer worked perfectly as normal. But what about when we want to set some other properties? Without any time zones, that&amp;#39;s fine:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; source = &lt;span class="Keyword"&gt;new&lt;/span&gt; FakeDateTimeZoneSource.Builder    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; VersionId = &lt;span class="String"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;    &lt;br /&gt;}.Build(); &lt;/div&gt;  &lt;p&gt;But how could we set &lt;code&gt;VersionId&lt;/code&gt; &lt;em&gt;and&lt;/em&gt; add some zones? This doesn&amp;#39;t work:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; invalid = &lt;span class="Keyword"&gt;new&lt;/span&gt; FakeDateTimeZoneSource.Builder    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; VersionId = &lt;span class="String"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;,    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; CreateZone(&lt;span class="String"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;),    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; CreateZone(&lt;span class="String"&gt;&amp;quot;y&amp;quot;&lt;/span&gt;)    &lt;br /&gt;}.Build(); &lt;/div&gt;  &lt;p&gt;That&amp;#39;s neither a valid object initializer (the second part doesn&amp;#39;t specify a field or property) nor a valid collection initializer (the first part &lt;em&gt;does&lt;/em&gt; set a property).&lt;/p&gt;  &lt;p&gt;In the end, I had to expose an &lt;code&gt;IList&amp;lt;DateTimeZone&amp;gt;&lt;/code&gt; property:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; valid = &lt;span class="Keyword"&gt;new&lt;/span&gt; FakeDateTimeZoneSource.Builder    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; VersionId = &lt;span class="String"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;,    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Zones = { CreateZone(&lt;span class="String"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;), CreateZone(&lt;span class="String"&gt;&amp;quot;y&amp;quot;&lt;/span&gt;) }    &lt;br /&gt;}.Build(); &lt;/div&gt;  &lt;p&gt;An alternative would have been to expose a propert of type &lt;code&gt;Builder&lt;/code&gt; which just returned itself - the same code would have been valid, but it would have been distinctly odd, and allowed some &lt;em&gt;really&lt;/em&gt; spurious code.&lt;/p&gt;  &lt;p&gt;I&amp;#39;m happy with the result in terms of the flexibility for clients - but the class design feels a bit messy, and I wouldn&amp;#39;t have wanted to expose this for the &amp;quot;production&amp;quot; assembly of Noda Time.&lt;/p&gt;  &lt;p&gt;Describing all of this to a colleague gave rise to the following rather sillier observation...&lt;/p&gt;  &lt;h1&gt;Is it an object initializer? Is it a collection initializer? (Parenthetically speaking...)&lt;/h1&gt;  &lt;p&gt;In a lot of C# code, an assignment expression is just a normal expression. That means there&amp;#39;s &lt;em&gt;potentially&lt;/em&gt; room for ambiguity, in exactly the same kind of situation as above - when sometimes we want a collection initializer, and sometimes we want an object initializer. Consider this sample class:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;    &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Collections;    &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Weird : IEnumerable    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; Foo { get; set; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; count;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; Count { get { &lt;span class="Statement"&gt;return&lt;/span&gt; count; } }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Add(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; x)    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; count++;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; IEnumerator IEnumerable.GetEnumerator()    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; NotSupportedException();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;As you can see, it doesn&amp;#39;t actually remember anything passed to the &lt;code&gt;Add&lt;/code&gt; method, but it does remember how many times we&amp;#39;ve called it.&lt;/p&gt;  &lt;p&gt;Now let&amp;#39;s try using &lt;code&gt;Weird&lt;/code&gt; in two ways which &lt;em&gt;only&lt;/em&gt; differ in terms of parentheses. First up, no parentheses:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; Foo = &lt;span class="String"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;;    &lt;br /&gt;Weird weird = &lt;span class="Keyword"&gt;new&lt;/span&gt; Weird { Foo = &lt;span class="String"&gt;&amp;quot;y&amp;quot;&lt;/span&gt; };    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;Console.WriteLine(Foo);&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// x&lt;/span&gt;    &lt;br /&gt;Console.WriteLine(weird.Foo);&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// y&lt;/span&gt;    &lt;br /&gt;Console.WriteLine(weird.Count); &lt;span class="InlineComment"&gt;// 0&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;Okay, so it&amp;#39;s odd having a local variable called &lt;code&gt;Foo&lt;/code&gt;, but we&amp;#39;re basically fine. This is an &lt;em&gt;object&lt;/em&gt; initializer, and it&amp;#39;s setting the &lt;code&gt;Foo&lt;/code&gt; property within the new &lt;code&gt;Weird&lt;/code&gt; instance. Now let&amp;#39;s add a pair of parentheses:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; Foo = &lt;span class="String"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;;    &lt;br /&gt;Weird weird = &lt;span class="Keyword"&gt;new&lt;/span&gt; Weird { (Foo = &lt;span class="String"&gt;&amp;quot;y&amp;quot;&lt;/span&gt;) };    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;Console.WriteLine(Foo);&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// y&lt;/span&gt;    &lt;br /&gt;Console.WriteLine(weird.Foo);&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Nothing (null)&lt;/span&gt;    &lt;br /&gt;Console.WriteLine(weird.Count); &lt;span class="InlineComment"&gt;// 1&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;Just adding those parenthese turn the object initializer into a collection initializer, whose sole item is the result of the assignment operator - which is the value which has now been assigned to &lt;code&gt;Foo&lt;/code&gt;.&lt;/p&gt;  &lt;p&gt;Needless to say, I &lt;em&gt;don&amp;#39;t&lt;/em&gt; recommend using this approach in real code...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1823825" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/24RyeQVpi8Y" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2013/02/14/fun-with-object-and-collection-initializers.aspx</feedburner:origLink></item><item><title>Stack Overflow question checklist</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/_QzxQfuWC9A/stack-overflow-question-checklist.aspx</link><pubDate>Sat, 24 Nov 2012 09:22:28 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1819786</guid><dc:creator>skeet</dc:creator><slash:comments>17</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1819786</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1819786</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/11/24/stack-overflow-question-checklist.aspx#comments</comments><description>&lt;p&gt;My &lt;a href="http://tinyurl.com/so-hints"&gt;earlier post&lt;/a&gt; on how to write a good question is pretty long, and I suspect that even when I refer people to it, often they don&amp;#39;t bother reading it. So here&amp;#39;s a short list of questions to check after you&amp;#39;ve written a question (and to think about &lt;em&gt;before&lt;/em&gt; you write the question):&lt;/p&gt;  &lt;li&gt;Have you done some research before asking the question? &lt;sup&gt;1&lt;/sup&gt; &lt;/li&gt;  &lt;li&gt;Have you explained what you&amp;#39;ve already tried to solve your problem? &lt;/li&gt;  &lt;li&gt;Have you specified which language and platform you&amp;#39;re using, including version number where relevant? &lt;/li&gt;  &lt;li&gt;If your question includes code, have you written it as a short but complete program? &lt;sup&gt;2&lt;/sup&gt; &lt;/li&gt;  &lt;li&gt;If your question includes code, have you checked that it&amp;#39;s correctly formatted? &lt;sup&gt;3&lt;/sup&gt; &lt;/li&gt;  &lt;li&gt;If your code doesn&amp;#39;t compile, have you included the exact compiler error? &lt;/li&gt;  &lt;li&gt;If your question &lt;em&gt;doesn&amp;#39;t&lt;/em&gt; include code, are you sure it shouldn&amp;#39;t? &lt;/li&gt;  &lt;li&gt;If your program throws an exception, have you included the exception, with both the message and the stack trace? &lt;/li&gt;  &lt;li&gt;If your program produces different results to what you expected, have you stated what you expected, &lt;em&gt;why &lt;/em&gt;you expected it, and the actual results? &lt;/li&gt;  &lt;li&gt;If your question is related to anything locale-specific (languages, time zones) have you stated the relevant information about your system (e.g. your current time zone)? &lt;/li&gt;  &lt;li&gt;Have you checked that your question looks reasonable in terms of formatting? &lt;/li&gt;  &lt;li&gt;Have you checked the spelling and grammar to the best of your ability? &lt;sup&gt;4&lt;/sup&gt; &lt;/li&gt;  &lt;li&gt;Have you read the whole question to yourself carefully, to make sure it makes sense and contains enough information for someone coming to it without any of the context that you already know?    &lt;p&gt;If the answer to any of these questions is &amp;quot;no&amp;quot; you should take the time to fix up your question before posting. I realize this may seem like a lot of effort, but it will help you to get a useful answer as quickly as possible. Don&amp;#39;t forget that you&amp;#39;re basically asking other people to help you out of the goodness of their heart - it&amp;#39;s up to you to do all you can to make that as simple as possible.&lt;/p&gt;    &lt;hr /&gt;    &lt;p&gt;&lt;sup&gt;1&lt;/sup&gt; If you went from &amp;quot;something&amp;#39;s not working&amp;quot; to &amp;quot;asking a question&amp;quot; in less than 10 minutes, you probably haven&amp;#39;t done enough research.&lt;/p&gt;    &lt;p&gt;&lt;sup&gt;2&lt;/sup&gt; Ideally anyone answering the question should be able to copy your code, paste it into a text editor, compile it, run it, and observe the problem. Console applications are good for this - unless your question is directly about a user interface aspect, prefer to write a short console app. Remove anything not directly related to your question, but keep it complete enough to run.&lt;/p&gt;    &lt;p&gt;&lt;sup&gt;3&lt;/sup&gt; Try to avoid code which makes users scroll horizontally. You may well need to change how you split lines from how you have it in your IDE. Take the time to make it as clear as possible for those trying to help you.&lt;/p&gt;    &lt;p&gt;&lt;sup&gt;4&lt;/sup&gt; I realize that English isn&amp;#39;t the first language for many Stack Overflow users. We&amp;#39;re not looking for perfection - just some effort. If you know your English isn&amp;#39;t good, see if a colleague or friend can help you with your question before you post it.&lt;/p&gt;     &lt;/li&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1819786" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/_QzxQfuWC9A" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/11/24/stack-overflow-question-checklist.aspx</feedburner:origLink></item><item><title>Noda Time v1.0 released</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/pQJt1QF_W90/noda-time-v1-0-released.aspx</link><pubDate>Wed, 07 Nov 2012 23:36:44 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1818929</guid><dc:creator>skeet</dc:creator><slash:comments>13</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1818929</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1818929</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/11/07/noda-time-v1-0-released.aspx#comments</comments><description>&lt;p&gt;Go get Noda Time 1.0!&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://nuget.org/packages/NodaTime/1.0.0"&gt;NuGet package&lt;/a&gt; (and the &lt;a href="http://nuget.org/packages/NodaTime.Testing/1.0.0"&gt;testing package&lt;/a&gt;) &lt;/li&gt;    &lt;li&gt;&lt;a href="https://code.google.com/p/noda-time"&gt;Project home page&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="https://code.google.com/p/noda-time/downloads/list"&gt;Project downloads page&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://noda-time.googlecode.com/hg-history/1.0.x/docs/userguide/index.html"&gt;v1.0 user guide&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://noda-time.googlecode.com/hg-history/1.0.x/docs/api/Index.html"&gt;v1.0 API reference&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Today is the end of the longest release cycle I&amp;#39;ve been personally involved in. On November 5th 2009, I &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2009/11/05/what-s-in-a-name-again.aspx"&gt;announced my intention&lt;/a&gt; to write a port of Joda Time for .NET. &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2009/11/06/noda-time-is-born.aspx"&gt;The next day, Noda Time was born&lt;/a&gt; - with a lofty (foolhardy) set of targets.&lt;/p&gt;  &lt;p&gt;Near the end of a talk *about* Noda Time this evening, I released Noda Time 1.0.0.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s taken three years, but I&amp;#39;m immensely proud of what we&amp;#39;ve managed to achieve. We&amp;#39;re far from &amp;quot;done&amp;quot; but I believe we&amp;#39;re already significantly ahead of most other date/time APIs I&amp;#39;ve seen in terms of providing a clean API which reduces *incidental* complexity while highlighting the *inherent* complexity of the domain. (This is a theme I&amp;#39;m becoming dogmatic about on various fronts.)&lt;/p&gt;  &lt;p&gt;There&amp;#39;s more to do - I can&amp;#39;t see myself considering Noda Time to be &amp;quot;done&amp;quot; any time soon - but hopefully now we&amp;#39;ve got a stable release, we can start to build user momentum.&lt;/p&gt;  &lt;p&gt;One point I raised at the &lt;a href="http://www.dotnetdevnet.com"&gt;DotNetDevNet&lt;/a&gt; presentation tonight was that there&amp;#39;s a definite benefit (in my very biased view) in just *looking into* Noda Time:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;If you can&amp;#39;t use it in your production code, use it when prototyping &lt;/li&gt;    &lt;li&gt;If you can&amp;#39;t use it in your prototype code, play with it in personal projects &lt;/li&gt;    &lt;li&gt;If you can&amp;#39;t use it in personal projects, read the user guide to understand the concepts &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I hope that simply looking at the various types that Noda Time providers will give you more insight into how you should be thinking about date and time handling in your code. While the BCL API has a lot of flaws, you can work around most of them if you make it crystal clear what your data means at every step. The type system will leave that largely ambiguous, but there&amp;#39;s nothing to stop you from naming your variables descriptively, and adding appropriate    &lt;br /&gt;comments.&lt;/p&gt;  &lt;p&gt;Of course, I would far prefer it if you&amp;#39;d start using Noda Time and raising issues on how to make it better. Spread the word.&lt;/p&gt;  &lt;p&gt;Oh, and if anyone from the BCL team is reading this and would like to include something like Noda Time into .NET 5 as a &amp;quot;next generation&amp;quot; date/time, I&amp;#39;d be *really* interested in talking to you :)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1818929" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/pQJt1QF_W90" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Noda+Time/default.aspx">Noda Time</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/11/07/noda-time-v1-0-released.aspx</feedburner:origLink></item><item><title>How can I enumerate thee? Let me count the ways...</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/NYBtwDYJqsE/how-can-i-enumerate-thee-let-me-count-the-ways.aspx</link><pubDate>Sun, 30 Sep 2012 18:58:21 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1817580</guid><dc:creator>skeet</dc:creator><slash:comments>19</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1817580</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1817580</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/09/30/how-can-i-enumerate-thee-let-me-count-the-ways.aspx#comments</comments><description>&lt;p&gt;This weekend, I was writing some demo code for the async chapter of C# in Depth - the idea was to decompile a simple asynchronous method and see what happened. I received quite a surprise during this, in a way which had nothing to do with asynchrony.&lt;/p&gt;  &lt;p&gt;Given that at execution time, &lt;code&gt;text&lt;/code&gt; refers to an instance of &lt;code&gt;System.String&lt;/code&gt;, and assuming nothing in the body of the loop captures the &lt;code&gt;ch&lt;/code&gt; variable, how would you expect the following loop to be compiled?&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="ValueType"&gt;char&lt;/span&gt; ch &lt;span class="Statement"&gt;in&lt;/span&gt; text)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Body here&lt;/span&gt;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Before today, I could think of four answers depending on the compile-time type of &lt;code&gt;text&lt;/code&gt;, assuming it compiled at all. One of those answers is if &lt;code&gt;text&lt;/code&gt; is declared to be &lt;code&gt;dynamic&lt;/code&gt;, which I&amp;#39;m not going to go into here. Let&amp;#39;s stick with static typing.&lt;/p&gt;  &lt;h2&gt;If &lt;code&gt;text&lt;/code&gt; is declared as &lt;code&gt;IEnumerable&lt;/code&gt;...&lt;/h2&gt;  &lt;p&gt;In this case, the compiler can only use the non-generic &lt;code&gt;IEnumerator&lt;/code&gt; interface, and I&amp;#39;d expect the code to be roughly equivalent to this:&lt;/p&gt;  &lt;div class="code"&gt;IEnumerator iterator = text.GetEnumerator();    &lt;br /&gt;&lt;span class="Statement"&gt;try&lt;/span&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;while&lt;/span&gt; (iterator.MoveNext())     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;char&lt;/span&gt; ch = (&lt;span class="ValueType"&gt;char&lt;/span&gt;) iterator.Current;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Body here&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;}     &lt;br /&gt;&lt;span class="Statement"&gt;finally&lt;/span&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; IDisposable disposable = iterator &lt;span class="Keyword"&gt;as&lt;/span&gt; IDisposable;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (disposable != &lt;span class="Keyword"&gt;null&lt;/span&gt;)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; disposable.Dispose();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Note how the disposal of the iterator has to be conditional, as &lt;code&gt;IEnumerator&lt;/code&gt; doesn&amp;#39;t extend &lt;code&gt;IDisposable&lt;/code&gt;. &lt;/p&gt;  &lt;h2&gt;If &lt;code&gt;text&lt;/code&gt; is declared as &lt;code&gt;IEnumerable&amp;lt;char&amp;gt;&lt;/code&gt;...&lt;/h2&gt;  &lt;p&gt;Here, we don&amp;#39;t need any execution time casting, and the disposal can be unconditional:&lt;/p&gt;  &lt;div class="code"&gt;IEnumerator&amp;lt;&lt;span class="ValueType"&gt;char&lt;/span&gt;&amp;gt; iterator = text.GetEnumerator();     &lt;br /&gt;&lt;span class="Statement"&gt;try&lt;/span&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;while&lt;/span&gt; (iterator.MoveNext())     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;char&lt;/span&gt; ch = iterator.Current;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Body here&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;}     &lt;br /&gt;&lt;span class="Statement"&gt;finally&lt;/span&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; iterator.Dispose();     &lt;br /&gt;} &lt;/div&gt;  &lt;h2&gt;If &lt;code&gt;text&lt;/code&gt; is declared as &lt;code&gt;string&lt;/code&gt;...&lt;/h2&gt;  &lt;p&gt;Now things get interesting. &lt;code&gt;System.String&lt;/code&gt; implements &lt;code&gt;IEnumerable&amp;lt;char&amp;gt;&lt;/code&gt; using explicit interface implementation, and exposes a &lt;a href="http://msdn.microsoft.com/en-us/library/system.string.getenumerator.aspx"&gt;separate public &lt;code&gt;GetEnumerator()&lt;/code&gt; method&lt;/a&gt; which is declared to return a &lt;a href="http://msdn.microsoft.com/en-us/library/system.charenumerator.aspx"&gt;&lt;code&gt;CharEnumerator&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Usually when I find a type doing this sort of thing, it&amp;#39;s for the sake of efficiency, to reduce heap allocations. For example, &lt;a href="http://msdn.microsoft.com/en-us/library/b0yss765.aspx"&gt;&lt;code&gt;List&amp;lt;T&amp;gt;.GetEnumerator&lt;/code&gt;&lt;/a&gt; returns a &lt;a href="http://msdn.microsoft.com/en-us/library/x854yt9s.aspx"&gt;&lt;code&gt;List&amp;lt;T&amp;gt;.Enumerator&lt;/code&gt;&lt;/a&gt; which is &lt;i&gt;struct&lt;/i&gt; with the appropriate iteration members. This means if you use &lt;code&gt;foreach&lt;/code&gt; over an expression of type &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt;, the iterator can stay on the stack in most cases, saving object allocation and garbage collection.&lt;/p&gt;  &lt;p&gt;In this case, however, I suspect &lt;code&gt;CharEnumerator&lt;/code&gt; was introduced (way back in .NET 1.0) to avoid having to box each character in the string. This was one reason for &lt;code&gt;foreach&lt;/code&gt; handling to be based on types obeying the enumerable pattern, as well as there being support through the normal interfaces. It strikes me that it could still have been a structure in the same way as for &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt;, but maybe that wasn&amp;#39;t considered as an option.&lt;/p&gt;  &lt;p&gt;Anyway, it means that I would have &lt;i&gt;expected&lt;/i&gt; the code to be compiled like this, even back to C# 1:&lt;/p&gt;  &lt;div class="code"&gt;CharEnumerator iterator = text.GetEnumerator();    &lt;br /&gt;&lt;span class="Statement"&gt;try&lt;/span&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;while&lt;/span&gt; (iterator.MoveNext())     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;char&lt;/span&gt; ch = iterator.Current;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Body here&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;}     &lt;br /&gt;&lt;span class="Statement"&gt;finally&lt;/span&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; iterator.Dispose();     &lt;br /&gt;} &lt;/div&gt;  &lt;h2&gt;What really happens when &lt;code&gt;text&lt;/code&gt; is declared as &lt;code&gt;string&lt;/code&gt;...&lt;/h2&gt;  &lt;p&gt;(This is the bit that surprised me.) &lt;/p&gt;  &lt;p&gt;So far, I&amp;#39;ve been assuming that the C# compiler doesn&amp;#39;t have any special knowledge about strings, when it comes to iteration. I knew it did for arrays, but that&amp;#39;s all. The &lt;i&gt;actual&lt;/i&gt; result - under the C# 5 compiler, at least - is to use the &lt;code&gt;Length&lt;/code&gt; property and the indexer directly:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ValueType"&gt;int&lt;/span&gt; index = 0;     &lt;br /&gt;&lt;span class="Statement"&gt;while&lt;/span&gt; (index &amp;lt; text.Length)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;char&lt;/span&gt; ch = text[index];     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; index++;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Body here&lt;/span&gt;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;There&amp;#39;s no heap allocation, and no &lt;code&gt;Dispose&lt;/code&gt; call. If the variable in question can change its value within the loop (e.g. if it&amp;#39;s a field, or a captured variable, or there&amp;#39;s an assignment to it within the body) then a copy is made of the variable value (just a reference, of course) first, so that all member access is performed on the same object. &lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;So, there we go. There&amp;#39;s nothing particularly mind-blowing here - certainly nothing to affect your programming style, unless you were deliberately avoiding using &lt;code&gt;foreach&lt;/code&gt; on strings &amp;quot;because it&amp;#39;s slow.&amp;quot; It&amp;#39;s still a good lesson in not assuming you know what the compiler is going to do though... so long as the results are as expected, I&amp;#39;m very happy for them to put extra smarts in, even if it does mean having to change my C# in Depth sample code a bit...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1817580" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/NYBtwDYJqsE" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/09/30/how-can-i-enumerate-thee-let-me-count-the-ways.aspx</feedburner:origLink></item><item><title>Stack Overflow and personal emails</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/iLSsE2XOeCI/stack-overflow-and-personal-emails.aspx</link><pubDate>Wed, 22 Aug 2012 17:51:24 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1815372</guid><dc:creator>skeet</dc:creator><slash:comments>33</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1815372</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1815372</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/08/22/stack-overflow-and-personal-emails.aspx#comments</comments><description>&lt;p&gt;This post is partly meant to be a general announcement, and partly meant to be something I can point people at in the future (rather than writing a short version of this on each email).&lt;/p&gt;  &lt;p&gt;These days, I get at least a few emails practically &lt;em&gt;every day&lt;/em&gt; along the lines of:&lt;/p&gt;  &lt;p&gt;&amp;quot;I saw you on Stack Overflow, and would like you to answer this development question for me...&amp;quot;&lt;/p&gt;  &lt;p&gt;It&amp;#39;s clear that the author:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Is aware of Stack Overflow&lt;/li&gt;    &lt;li&gt;Is aware that Stack Overflow is a site for development Q&amp;amp;A&lt;/li&gt;    &lt;li&gt;Is aware that I answer questions on Stack Overflow&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;... and yet they believe that the right way of getting me to answer a question is by emailing it to me directly. Sometimes it&amp;#39;s a link to a Stack Overflow question, sometimes it&amp;#39;s the question asked directly in email.&lt;/p&gt;  &lt;p&gt;In the early days of Stack Overflow, this wasn&amp;#39;t too bad. I&amp;#39;d get maybe one email like this a week. Nowadays, it&amp;#39;s simply too much.&lt;/p&gt;  &lt;p&gt;If you have a question worthy of Stack Overflow, ask it on Stack Overflow. If you&amp;#39;ve been banned from asking questions due to asking too many low-quality ones before, then I&amp;#39;m unlikely to enjoy answering your questions by email - learn &lt;a href="http://tinyurl.com/so-hints"&gt;what makes a good question&lt;/a&gt; instead, and edit your existing questions.&lt;/p&gt;  &lt;p&gt;If you&amp;#39;ve already asked the question on Stack Overflow, you should consider why you think it&amp;#39;s more worthy of my attention than everyone else&amp;#39;s questions. You should also consider what would happen if &lt;em&gt;everyone&lt;/em&gt; who would like me to answer a question decided to email me.&lt;/p&gt;  &lt;p&gt;Of course in &lt;em&gt;some&lt;/em&gt; cases it&amp;#39;s appropriate. If you&amp;#39;ve already asked a question, written it as well as you can, waited a while to see if you get any answers naturally, &lt;em&gt;and&lt;/em&gt; if it&amp;#39;s in an area that you know I&amp;#39;m particularly experienced in (read: the C# language, basically) then that&amp;#39;s fine. If your question is about something from C# in Depth - a snippet which doesn&amp;#39;t work or some text you don&amp;#39;t understand, for example - then it&amp;#39;s entirely appropriate to mail me directly.&lt;/p&gt;  &lt;p&gt;Basically, ask yourself whether you think I will actually welcome the email. Is it about something you know I&amp;#39;m specifically interested in? Or are you just trying to get more attention to a question, somewhat like jumping a queue?&lt;/p&gt;  &lt;p&gt;I&amp;#39;m aware that it&amp;#39;s possible this post makes me look either like a grumpy curmudgeon or (worse) like an egocentric pseudo-celebrity. The truth is I&amp;#39;m just like everyone else, with very little time on my hands - time I&amp;#39;d like to spend as usefully and fairly as possible.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1815372" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/iLSsE2XOeCI" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/General/default.aspx">General</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/08/22/stack-overflow-and-personal-emails.aspx</feedburner:origLink></item><item><title>The future of "C# in Depth"</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/xkjNKrOKEwk/the-future-of-quot-c-in-depth-quot.aspx</link><pubDate>Sat, 04 Aug 2012 08:19:19 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1814752</guid><dc:creator>skeet</dc:creator><slash:comments>13</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1814752</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1814752</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/08/04/the-future-of-quot-c-in-depth-quot.aspx#comments</comments><description>&lt;p&gt;I&amp;#39;m getting fairly frequent questions - mostly on Twitter - about whether there&amp;#39;s going to be a third edition of C# in Depth. I figure it&amp;#39;s worth answering it once in some detail rather than repeatedly in 140 characters ;)&lt;/p&gt;  &lt;p&gt;I&amp;#39;m currently writing a couple of new chapters covering the new features in C# 5 - primarily async, of course. The current &amp;quot;plan&amp;quot; is that these will be added to the existing 2nd edition to create a 3rd edition. There will be minimal changes to the existing text of the 2nd edition - basically going over the &lt;a href="http://csharpindepth.com/Errata.aspx"&gt;errata&lt;/a&gt; and editing a few places which ought to mention C# 5 early. (In particular the changes to how foreach loop variables are captured.)&lt;/p&gt;  &lt;p&gt;So there will definitely be new chapters. I&amp;#39;m hoping there&amp;#39;ll be a full new print (and ebook of course) edition, but no contracts have been signed yet. I&amp;#39;m &lt;em&gt;hoping&lt;/em&gt; that the new chapters will be provided free electronically to anyone who&amp;#39;s already got the ebook of the 2nd edition - but we&amp;#39;ll see. Oh, and I don&amp;#39;t have any timelines at the moment. Work is more demanding than it was when I was writing the first and second editions, but obviously I&amp;#39;ll try to get the job done at a reasonable pace. (Writing about async in a way which is both accessible and accurate is really tricky, by the way.)&lt;/p&gt;  &lt;p&gt;Of course when I&amp;#39;ve finished those, I&amp;#39;ve got two other C# books I &lt;em&gt;want&lt;/em&gt; to be writing... when I&amp;#39;m not working on Noda Time, Tekpub screencasts etc...&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Update&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I had a question on Twitter around the &amp;quot;two other C# books&amp;quot;. I don&amp;#39;t want to go into too many details - partly because they&amp;#39;re very likely to change - but my intention is to write &amp;quot;C# from Scratch&amp;quot; and &amp;quot;C# in Style&amp;quot;. The first would be for complete beginners; the second wouldn&amp;#39;t go into &amp;quot;how things work&amp;quot; so much as &amp;quot;how to use the language most effectively.&amp;quot; (Yes, competition for Effective C#.) One possibility is that both would be donationware, at least in ebook form, ideally with community involvement in terms of public comments.&lt;/p&gt;  &lt;p&gt;I&amp;#39;m hoping that both will use the same codebase as an extended example, where &amp;quot;From Scratch&amp;quot; would explain what the code does, and &amp;quot;In Style&amp;quot; would explain why I chose that approach. Oh, and &amp;quot;From Scratch&amp;quot; would use unit testing as a teaching tool wherever possible, attempting to convey the idea that it&amp;#39;s something every self-respecting dev does :)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1814752" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/xkjNKrOKEwk" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Books/default.aspx">Books</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/08/04/the-future-of-quot-c-in-depth-quot.aspx</feedburner:origLink></item><item><title>The perils of conditional mutability</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/BISytg6yMcs/the-perils-of-conditional-mutability.aspx</link><pubDate>Sun, 06 May 2012 13:58:45 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1809562</guid><dc:creator>skeet</dc:creator><slash:comments>6</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1809562</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1809562</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/05/06/the-perils-of-conditional-mutability.aspx#comments</comments><description>&lt;p&gt;This morning I was wrestling with trying to make some Noda Time unit tests faster. For some reason, the &lt;a href="http://teamcity.codebetter.com"&gt;continuous integration host we&amp;#39;re using&lt;/a&gt; is &lt;em&gt;really&lt;/em&gt; slow at loading resources under .NET 4. The unit tests which run in 10 seconds on my home laptop take over three &lt;em&gt;hours&lt;/em&gt; on the continuous integration system. Taking stack traces at regular intervals showed the problem was with the NodaFormatInfo constructor, which reads some resources.&lt;/p&gt;  &lt;p&gt;I may look into streamlining the resource access later, but before we get to that point, I wanted to try to reduce the number of times we call that constructor in the first place. NodaFormatInfo is meant to be cached, so I wouldn&amp;#39;t have expected thousands of instances to be created - but it&amp;#39;s only cached when the System.Globalization.CultureInfo it&amp;#39;s based on is read-only. This is where the problems start...&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx"&gt;CultureInfo&lt;/a&gt; is &lt;em&gt;conditionally mutable &lt;/em&gt;(not an official term, just one I&amp;#39;ve coined for the purposes of this post). You can ask whether or not it&amp;#39;s read-only with the &lt;a href="http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.isreadonly.aspx"&gt;IsReadOnly property&lt;/a&gt;, and obviously if it&amp;#39;s read-only you can&amp;#39;t change it. Additionally, CultureInfo is composed of other conditionally mutable objects - &lt;a href="http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx"&gt;DateTimeFormatInfo&lt;/a&gt;, &lt;a href="http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx"&gt;NumberFormatInfo&lt;/a&gt; etc. There&amp;#39;s a static &lt;a href="http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.readonly.aspx"&gt;ReadOnly method&lt;/a&gt; on CultureInfo to create a read-only wrapper around a mutable CultureInfo. It&amp;#39;s not clearly documented whether that&amp;#39;s &lt;em&gt;expected&lt;/em&gt; to take a deep copy (so that callers can really rely on it not changing) or whether it&amp;#39;s expected to reflect any further changes made to the culture info it&amp;#39;s based on. To go in the other direction, you can call Clone on a CultureInfo to create a mutable copy of any existing culture.&lt;/p&gt;  &lt;p&gt;Further complications are introduced by the properties on the composite objects - we have properties such as &lt;a href="http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.monthnames.aspx"&gt;DateTimeFormatInfo.MonthNames&lt;/a&gt; which returns a string array. Remember, arrays are &lt;em&gt;always&lt;/em&gt; mutable. So it&amp;#39;s really important to know whether the array reference returned from the property refers to a &lt;em&gt;copy&lt;/em&gt; of the underlying data, or whether it refers to the array that&amp;#39;s used internally by the type. Obviously for read-only DateTimeFormatInfo objects, I&amp;#39;d expect a copy to be returned - but for a mutable DateTimeFormatInfo, it would potentially make sense to return the underlying array reference. Unfortunately, the documentation doesn&amp;#39;t make this clear - but in practice, it always returns a copy. If you need to change the month names, you need to clone the array, mutate the clone, and then set the MonthNames property.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;All of this makes CultureInfo hard to work with&lt;/em&gt;. The caching decision earlier on only really works if a &amp;quot;read-only&amp;quot; culture genuinely won&amp;#39;t change behind the scenes. The type system gives you no help to catch subtle bugs at compile-time. Making any of this robust but efficient (in terms of taking minimal copies) is tricky to say the least.&lt;/p&gt;  &lt;p&gt;Not only does it make it hard to work with from a client&amp;#39;s point of view, but apparently it&amp;#39;s hard to implement correctly too...&lt;/p&gt;  &lt;h2&gt;First bug: Mono&amp;#39;s invariant culture isn&amp;#39;t terribly invariant...&lt;/h2&gt;  &lt;p&gt;(Broken in 2.10.8; apparently fixed later.)&lt;/p&gt;  &lt;p&gt;I discovered this while getting Noda Time&amp;#39;s unit tests to pass on Mono. Unfortunately there are some I&amp;#39;ve had to effectively disable at the moment, due to deficiencies in Mono (some of which are being fixed, of course).&lt;/p&gt;  &lt;p&gt;Here&amp;#39;s a program which builds a clone of the invariant culture, changes the &lt;em&gt;clone&amp;#39;s&lt;/em&gt; genitive month names, and then prints out the first &lt;em&gt;non-genitive&lt;/em&gt; name from the plain invariant culture:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;     &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Globalization;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Test     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CultureInfo clone = (CultureInfo) CultureInfo.InvariantCulture.Clone();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Note: not even deliberately changing MonthNames for this culture!&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; clone.DateTimeFormat.MonthGenitiveNames[0] = &lt;span class="String"&gt;&amp;quot;Changed&amp;quot;&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Prints Changed&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(CultureInfo.InvariantCulture.DateTimeFormat.MonthNames[0]);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;I believe this bug is &lt;em&gt;really&lt;/em&gt; due to the lack of support for genitive month names in Mono at the moment - the MonthGenitiveNames property always just returns a reference to the month names for the invariant culture - without taking a copy first. (It always returns the invariant culture&amp;#39;s month names, even if you&amp;#39;re using a different culture entirely.) The code above shows an &amp;quot;innocent&amp;quot; attempt to change a mutable clone - but in reality we could have used &lt;em&gt;any&lt;/em&gt; culture (including an immutable one) to make the change.&lt;/p&gt;  &lt;p&gt;Note that in the .NET implementation, the change would only have been to a copy of the underlying data, so even the &lt;em&gt;clone&lt;/em&gt; wouldn&amp;#39;t have reflected change anywhere.&lt;/p&gt;  &lt;h2&gt;Second bug: ReadOnly losing changes&lt;/h2&gt;  &lt;p&gt;The second bug is the one I found this morning. It looks like it&amp;#39;s fixed in .NET 4, but it&amp;#39;s present in .NET 3.5, which is where it bit me this morning. When you try to make a read-only wrapper around a mutated culture, some of the properties are preserved... but some aren&amp;#39;t:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;    &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Globalization;    &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Test    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CultureInfo clone = (CultureInfo) CultureInfo.InvariantCulture.Clone();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; clone.DateTimeFormat.AMDesignator = &lt;span class="String"&gt;&amp;quot;ChangedAm&amp;quot;&lt;/span&gt;;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// The array is recreated on each call to MonthNames, so changing the&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// value within the array itself doesn&amp;#39;t work :(&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt;[] months = (&lt;span class="ReferenceType"&gt;string&lt;/span&gt;[]) clone.DateTimeFormat.MonthNames;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; months[0] = &lt;span class="String"&gt;&amp;quot;ChangedMonth&amp;quot;&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; clone.DateTimeFormat.MonthNames = months;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CultureInfo readOnlyCopy = CultureInfo.ReadOnly(clone);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(clone.DateTimeFormat.AMDesignator); &lt;span class="InlineComment"&gt;// ChangedAm&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(clone.DateTimeFormat.MonthNames[0]); &lt;span class="InlineComment"&gt;// ChangedMonth&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(readOnlyCopy.DateTimeFormat.AMDesignator); &lt;span class="InlineComment"&gt;// ChangedAm&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(readOnlyCopy.DateTimeFormat.MonthNames[0]); &lt;span class="InlineComment"&gt;// January (!)&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;I don&amp;#39;t know what&amp;#39;s going on here. In the end I just left the test code using the mutable clone, having added a comment explaining &lt;em&gt;why&lt;/em&gt; it wasn&amp;#39;t created a read-only wrapper.&lt;/p&gt;  &lt;p&gt;I&amp;#39;ve experimented with a few different options here, including setting the MonthNames property on the clone &lt;em&gt;after&lt;/em&gt; creating the wrapper. No joy - I simply can&amp;#39;t make the new month names stick in the read-only copy. &amp;lt;sigh&amp;gt;&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;I&amp;#39;ve been frustrated by the approach we&amp;#39;ve taken to cultures in Noda Time for a while. I haven&amp;#39;t worked out exactly what we should do about it yet, so it&amp;#39;s likely to stay somewhat annoying for v1, but I may well revisit it significantly for v2. Unfortunately, there&amp;#39;s nothing I can do about CultureInfo itself.&lt;/p&gt;  &lt;p&gt;What I would have &lt;em&gt;preferred&lt;/em&gt; in all of this is the builder pattern: make CultureInfo, DateTimeFormatInfo etc all immutable, but give each of them mutable builder types, with the ability to create a mutable builder based on an existing immutable instance, and obviously to create a new immutable instance from a builder. That would make all kinds of things simpler - including caching.&lt;/p&gt;  &lt;p&gt;For the moment though, I hope we can all learn lessons from this - or have old lessons reinforced, at least:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Making a single type behave in different ways based on different &amp;quot;modes&amp;quot; makes it hard to use correctly. (Yes, this is the same first conclusion as with DateTime in the previous post. Funny, that.)&lt;/li&gt;    &lt;li&gt;Immutability has to be deep to be meaningful: it&amp;#39;s not much use having a supposedly read-only object which composes a StringBuilder...&lt;/li&gt;    &lt;li&gt;Arrays should be &lt;a href="http://blogs.msdn.com/b/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx"&gt;considered somewhat harmful&lt;/a&gt;. If you&amp;#39;re going to return an array from a method, make sure you document whether this is a &lt;em&gt;copy&lt;/em&gt; of the underlying data, or a &amp;quot;live&amp;quot; reference. (The latter should be very rare, particularly for a public API.) The exception here is if you return an empty array - that&amp;#39;s effectively immutable, so you can always return it with no problems.&lt;/li&gt;    &lt;li&gt;The builder pattern rocks - use it!&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In my next post I&amp;#39;ll try to get back to the TimeZoneInfo oddities I mentioned last time.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1809562" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/BISytg6yMcs" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Noda+Time/default.aspx">Noda Time</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Design/default.aspx">Design</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/05/06/the-perils-of-conditional-mutability.aspx</feedburner:origLink></item><item><title>More fun with DateTime</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/tSO4uPGTVe4/more-fun-with-datetime.aspx</link><pubDate>Wed, 02 May 2012 20:12:43 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1809416</guid><dc:creator>skeet</dc:creator><slash:comments>19</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1809416</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1809416</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/05/02/more-fun-with-datetime.aspx#comments</comments><description>&lt;p&gt;(Note that this is deliberately not posted in the &lt;a href="http://noda-time.blogspot.com/"&gt;Noda Time blog&lt;/a&gt;. I reckon it&amp;#39;s of wider interest from a design perspective, and I won&amp;#39;t be posting any of the equivalent &lt;a href="http://noda-time.googlecode.com"&gt;Noda Time&lt;/a&gt; code. I&amp;#39;ll just say now that we don&amp;#39;t have this sort of craziness in Noda Time, and leave it at that...)&lt;/p&gt;  &lt;p&gt;A few weeks ago, I was answering a Stack Overflow question when I noticed an operation around dates and times which &lt;em&gt;should&lt;/em&gt; have been losing information apparently not doing so. I investigated further, and discovered some &amp;quot;interesting&amp;quot; aspects of both DateTime and TimeZoneInfo. In an effort to keep this post down to a readable length (at least for most readers; certain WebDriver developers who shall remain nameless have probably given up by now already) I&amp;#39;ll save the TimeZoneInfo bits for another post.&lt;/p&gt;  &lt;h2&gt;Background: daylight saving transitions and ambiguous times&lt;/h2&gt;  &lt;p&gt;There&amp;#39;s one piece of &lt;em&gt;inherent&lt;/em&gt; date/time complexity you&amp;#39;ll need to understand for this post to make sense: sometimes, a local date/time occurs twice. For the purposes of this post, I&amp;#39;m going to assume you&amp;#39;re in the UK time zone. On October 28th 2012, at 2am local time (1am UTC), UK clocks will go back to 1am local time. So 1:20am local time occurs twice - once at 12:20am UTC (in daylight saving time, BST), and once at 1:20am UTC (in standard time, GMT).&lt;/p&gt;  &lt;p&gt;If you want to run any of the code in this post and you&amp;#39;re &lt;em&gt;not&lt;/em&gt; in the UK, please adjust the dates and times used to a similar ambiguity for when your clocks go back. If you happen to be in a time zone which doesn&amp;#39;t observe daylight savings, I&amp;#39;m afraid you&amp;#39;ll have to adjust your system time zone in order to see the effect for yourself.&lt;/p&gt;  &lt;h2&gt;DateTime.Kind and conversions&lt;/h2&gt;  &lt;p&gt;As you may already know, as of .NET 2.0, DateTime has a &lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.kind.aspx"&gt;Kind&lt;/a&gt; property, of type &lt;a href="http://msdn.microsoft.com/en-us/library/shx7s921.aspx"&gt;DateTimeKind&lt;/a&gt; - an enum with the following values:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Local: The DateTime is considered to be in the &lt;em&gt;system time zone&lt;/em&gt;. Not an arbitrary &amp;quot;local time in some time zone&amp;quot;, but in the specific current system time zone. &lt;/li&gt;    &lt;li&gt;Utc: The DateTime is considered to be in UTC (corollary: it always unambiguously represents an instant in time) &lt;/li&gt;    &lt;li&gt;Unspecified: This means different things in different contexts, but it&amp;#39;s a sort of &amp;quot;don&amp;#39;t know&amp;quot; kind; this is closer to &amp;quot;local time in some time zone&amp;quot; which is represented as LocalDateTime in Noda Time. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;DateTime provides three methods to convert between the kinds:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx"&gt;ToUniversalTime&lt;/a&gt;: if the original kind is Local or Unspecified, convert it from local time to universal time in the system time zone. If the original kind is Utc, this is a no-op. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx"&gt;ToLocalTime&lt;/a&gt;: if the original kind is Utc or Unspecified, convert it from UTC to local time. If the original kind is Local, this is a no-op. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.specifykind.aspx"&gt;SpecifyKind&lt;/a&gt;: keep the existing date/time, but &lt;em&gt;just&lt;/em&gt; change the kind. (So 7am stays as 7am, but it changes the &lt;em&gt;meaning&lt;/em&gt; of that 7am effectively.) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;(Prior to .NET 2.0, ToUniversalTime and ToLocalTime were already present, but always &lt;em&gt;assumed&lt;/em&gt; the original value needed conversion - so if you called x.ToLocalTime().ToLocalTime().ToLocalTime() the result would probably end up with the appropriate offset from UTC being applied three times!)&lt;/p&gt;  &lt;p&gt;Of course, none of these methods change the existing value - DateTime is immutable, and a value type - instead, they return a &lt;em&gt;new&lt;/em&gt; value.&lt;/p&gt;  &lt;h2&gt;DateTime&amp;#39;s Deep Dark Secret&lt;/h2&gt;  &lt;p&gt;(The code in this section is presented in several chunks, but it forms a single complete piece of code - later chunks refer to variables in earlier chunks. Put it all together in a Main method to run it.)&lt;/p&gt;  &lt;p&gt;Armed with the information in the previous sections, we should be able to make DateTime lose data. If we start with 12:20am UTC and 1:20am UTC on October 28th as DateTimes with a kind of Utc, when we convert them to local time (on a system in the UK time zone) we should get 1:20am in both cases due to the daylight saving transition. Indeed, that works:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Start with different UTC values around a DST transition&lt;/span&gt;     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; original1 = &lt;span class="Keyword"&gt;new&lt;/span&gt; DateTime(2012, 10, 28, 0, 20, 0, DateTimeKind.Utc);     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; original2 = &lt;span class="Keyword"&gt;new&lt;/span&gt; DateTime(2012, 10, 28, 1, 20, 0, DateTimeKind.Utc);     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Convert to local time&lt;/span&gt;     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local1 = original1.ToLocalTime();     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local2 = original2.ToLocalTime();     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Result is the same for both values. Information loss?&lt;/span&gt;     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; expected = &lt;span class="Keyword"&gt;new&lt;/span&gt; DateTime(2012, 10, 28, 1, 20, 0, DateTimeKind.Local);     &lt;br /&gt;Console.WriteLine(local1 == expected); &lt;span class="InlineComment"&gt;// True&lt;/span&gt;     &lt;br /&gt;Console.WriteLine(local2 == expected); &lt;span class="InlineComment"&gt;// True&lt;/span&gt;     &lt;br /&gt;Console.WriteLine(local1 == local2);&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// True&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;If we&amp;#39;ve started with two &lt;em&gt;different&lt;/em&gt; values, applied the same operation to both, and ended up with equal values, then we must have lost information, right? That doesn&amp;#39;t mean that operation is &amp;quot;bad&amp;quot; any more than &amp;quot;dividing by 2&amp;quot; is bad. You ought to be aware of that information loss, that&amp;#39;s all.&lt;/p&gt;  &lt;p&gt;So, we ought to be able to demonstrate that information loss further by converting back from local time to universal time. Here we have the opposite problem: from our local time of 1:20am, we have &lt;em&gt;two&lt;/em&gt; valid universal times we could convert to - either 12:20am UTC or 1:20am UTC. Both answers would be correct - they are universal times at which the local time would be 1:20am. So which one will get picked? Well... here&amp;#39;s the surprising bit:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Convert back to UTC &lt;/span&gt;    &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; roundTrip1 = local1.ToUniversalTime();&amp;#160; &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; roundTrip2 = local2.ToUniversalTime();     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Values round-trip correctly! Information has been recovered... &lt;/span&gt;    &lt;br /&gt;Console.WriteLine(roundTrip1 == original1);&amp;#160; &lt;span class="InlineComment"&gt;// True &lt;/span&gt;    &lt;br /&gt;Console.WriteLine(roundTrip2 == original2);&amp;#160; &lt;span class="InlineComment"&gt;// True &lt;/span&gt;    &lt;br /&gt;Console.WriteLine(roundTrip1 == roundTrip2); &lt;span class="InlineComment"&gt;// False&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;Somehow, each of the local values &lt;em&gt;knows&lt;/em&gt; which universal value it came from. The The information has been recovered, so the reverse conversion round-trips each value back to its original one. How is that possible?&lt;/p&gt;  &lt;p&gt;It turns out that DateTime actually has &lt;em&gt;four&lt;/em&gt; potential kinds: Local, Utc, Unspecified, and &amp;quot;local but treat it as the earlier option when resolving ambiguity&amp;quot;. A DateTime is really just a 64-bit number of ticks, but because the range of DateTime is only January 1st 0001 to December 31st 9999. That range can be represented in 62 bits, leaving 2 bits &amp;quot;spare&amp;quot; to represent the kind. 2 bits gives 4 possible values... the three documented ones and the shadowy extra one.&lt;/p&gt;  &lt;p&gt;Through experimentation, I&amp;#39;ve discovered that the kind is preserved if you perform arithmetic on the value, too... so if you go to another &amp;quot;fall back&amp;quot; DST transition such as October 30th 2011, the ambiguity resolution works the same way as before:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local3 = local1.AddYears(-1).AddDays(2);&amp;#160; &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local4 = local2.AddYears(-1).AddDays(2);&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;Console.WriteLine(local3.ToUniversalTime().Hour); &lt;span class="InlineComment"&gt;// 0 &lt;/span&gt;    &lt;br /&gt;Console.WriteLine(local4.ToUniversalTime().Hour); &lt;span class="InlineComment"&gt;// 1&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;If you use DateTime.SpecifyKind with DateTimeKind.Local, however, it goes back to the &amp;quot;normal&amp;quot; kind, even though it &lt;em&gt;looks&lt;/em&gt; like it should be a no-op:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Should be a no-op? &lt;/span&gt;    &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local5 = DateTime.SpecifyKind(local1, local1.Kind);&amp;#160; &lt;br /&gt;Console.WriteLine(local5.ToUniversalTime().Hour); &lt;span class="InlineComment"&gt;// 1&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;Is this correct behaviour? Or should it be a no-op, just like calling ToLocalTime on a &amp;quot;local&amp;quot; DateTime is? (Yes, I&amp;#39;ve checked - that doesn&amp;#39;t lose the information.) It&amp;#39;s hard to say, really, as this whole business appears to be undocumented... at least, I haven&amp;#39;t seen anything in MSDN about it. (Please add a link in the comments if you find something. The behaviour actually goes against what&amp;#39;s documented, as far as I can tell.)&lt;/p&gt;  &lt;p&gt;I haven&amp;#39;t looked into whether various forms of serialization preserve values like this faithfully, by the way - but you&amp;#39;d have to work hard to reproduce it in non-framework code. You can&amp;#39;t explicitly construct a DateTime with the &amp;quot;extra&amp;quot; kind; the only ways I know of to create such a value are via a conversion to local time or through arithmetic on a value which already has the kind. (Admittedly if you&amp;#39;re serializing a DateTime with a Kind of Local, you&amp;#39;re already on potentially shaky ground, given that you could be deserializing it on a machine with a different system time zone.)&lt;/p&gt;  &lt;h2&gt;Unkind comparisons&lt;/h2&gt;  &lt;p&gt;I&amp;#39;ve misled you a little, I have to admit. In the code above, when I compared the &amp;quot;expected&amp;quot; value with the results of the first conversions, I deliberately specified DateTimeKind.Local in the constructor call. After all, that&amp;#39;s the kind we &lt;em&gt;do&lt;/em&gt; expect. Well, yes - but I then printed the result of comparing this value with local1 and local2... and those comparisons would have been the same regardless of the kind I&amp;#39;d specified in the constructor.&lt;/p&gt;  &lt;p&gt;All comparisons between DateTimes ignore the Kind property. It&amp;#39;s not just restricted to equality. So for example, consider this comparison:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// In June: Local time is UTC+1, so 8am UTC is 9am local &lt;/span&gt;    &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; dt1 = &lt;span class="Keyword"&gt;new&lt;/span&gt; DateTime(2012, 6, 1, 8, 0, 0, DateTimeKind.Utc);&amp;#160; &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; dt2 = &lt;span class="Keyword"&gt;new&lt;/span&gt; DateTime(2012, 6, 1, 8, 30, 0, DateTimeKind.Local);&amp;#160; &lt;br /&gt;Console.WriteLine(dt1 &amp;lt; dt2); &lt;span class="InlineComment"&gt;// True&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;When viewed in terms of &amp;quot;what instants in time do these both represent?&amp;quot; the answer here is wrong - when you convert both values into the same time zone (in either direction), dt1 occurs &lt;em&gt;after&lt;/em&gt; dt2. But a simple look at the properties tells a different story. In practice, I suspect that most comparisons between DateTime values of different kinds involve code which is at best sloppy and is quite possibly broken in a meaningful way.&lt;/p&gt;  &lt;p&gt;Of course, if you bring Kind=Unspecified into the picture, it becomes impossible to compare meaningfully in a kind-sensitive way. Is 12am UTC before or after 1am Unspecified? It depends what time zone you later use.&lt;/p&gt;  &lt;p&gt;To be clear, it &lt;em&gt;is&lt;/em&gt; a hard-to-resolve issue, and one that we don&amp;#39;t do terribly well at in Noda Time at the moment for ZonedDateTime. (And even with just LocalDateTime you&amp;#39;ve got issues between calendars.) This is a situation where providing separate Comparer&amp;lt;T&amp;gt; implementations works nicely - so you can explicitly say what kind of comparison you want.&lt;/p&gt;  &lt;h2&gt;Conclusions&lt;/h2&gt;  &lt;p&gt;There&amp;#39;s more fun to be had with a similar situation when we look at TimeZoneInfo, but for now, a few lessons:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Giving a type different &amp;quot;modes&amp;quot; which make it mean fairly significantly different things is likely to cause headaches &lt;/li&gt;    &lt;li&gt;Keeping one of those modes secret (and preventing users from even constructing a value in that mode directly) leads to even more fun and games &lt;/li&gt;    &lt;li&gt;If two instances of your type are considered &amp;quot;equal&amp;quot; but behave differently, you should at least consider whether there&amp;#39;s something smelly going on &lt;/li&gt;    &lt;li&gt;There&amp;#39;s &lt;em&gt;always&lt;/em&gt; more fun to be had with DateTime... &lt;/li&gt; &lt;/ul&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1809416" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/tSO4uPGTVe4" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Evil+Code/default.aspx">Evil Code</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Noda+Time/default.aspx">Noda Time</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/05/02/more-fun-with-datetime.aspx</feedburner:origLink></item><item><title>Type initializer circular dependencies</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/aF_dVyhKyCg/type-initializer-circular-dependencies.aspx</link><pubDate>Sat, 07 Apr 2012 09:35:45 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1808561</guid><dc:creator>skeet</dc:creator><slash:comments>25</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1808561</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1808561</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/04/07/type-initializer-circular-dependencies.aspx#comments</comments><description>&lt;p&gt;To some readers, the title of this post may induce nightmarish recollections of late-night debugging sessions. To others it may be simply the epitome of jargon. Just to break the jargon down a bit:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Type initializer: the code executed to initialize the static variables of a class, and the static constructor &lt;/li&gt;    &lt;li&gt;Circular dependency: two bits of code which depend on each other - in this case, two classes whose type initializers each require that the other class is initialized &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;A quick example of the kind of problem I&amp;#39;m talking about would be helpful here. What would you expect this code to print?&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Test     &lt;br /&gt;{&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(First.Beta);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; First     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; Alpha = 5;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; Beta = Second.Gamma;     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Second     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; Gamma = First.Alpha;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Of course, without even glancing at the specification, any expectations are pretty irrelevant. Here&amp;#39;s what the spec (section 10.5.5.1 of the C# 4 version):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class. &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In addition to the language specification, the CLI specification gives more details about type initialization in the face of circular dependencies and multiple threads. I won&amp;#39;t post the details here, but the gist of it is:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Type initialization acts like a lock, to prevent more than one thread from initializing a type &lt;/li&gt;    &lt;li&gt;If the CLI notices that type A needs to be initialized in order to make progress, but it&amp;#39;s &lt;em&gt;already in the process&lt;/em&gt; of initializing type A &lt;em&gt;in the same thread&lt;/em&gt;, it continues as if the type were already initialized. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So here&amp;#39;s what you &lt;em&gt;might&lt;/em&gt; expect to happen:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Initialize Test: no further action required &lt;/li&gt;    &lt;li&gt;Start running Main &lt;/li&gt;    &lt;li&gt;Start initializing First (as we need First.Beta) &lt;/li&gt;    &lt;li&gt;Set First.Alpha to 5 &lt;/li&gt;    &lt;li&gt;Start initializing Second (as we need Second.Gamma) &lt;/li&gt;    &lt;li&gt;Set Second.Gamma to First.Alpha (5) &lt;/li&gt;    &lt;li&gt;End initializing Second &lt;/li&gt;    &lt;li&gt;Set First.Beta to Second.Gamma (5) &lt;/li&gt;    &lt;li&gt;End initializing First &lt;/li&gt;    &lt;li&gt;Print 5 &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Here&amp;#39;s what &lt;em&gt;actually&lt;/em&gt; happens - on my box, running .NET 4.5 beta. (I know that &lt;a href="https://msmvps.com/blogs/jon_skeet/archive/2010/01/26/type-initialization-changes-in-net-4-0.aspx"&gt;type initialization changed for .NET 4&lt;/a&gt;, for example. I don&amp;#39;t &lt;em&gt;know&lt;/em&gt; of any changes for .NET 4.5, but I&amp;#39;m not going to claim it&amp;#39;s impossible.)&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Initialize Test: no further action required &lt;/li&gt;    &lt;li&gt;Start running Main &lt;/li&gt;    &lt;li&gt;Start initializing First (as we need First.Beta) &lt;/li&gt;    &lt;li&gt;Start initializing Second (we &lt;em&gt;will&lt;/em&gt; need Second.Gamma) &lt;/li&gt;    &lt;li&gt;Set Second.Gamma to First.Alpha (0) &lt;/li&gt;    &lt;li&gt;End initializing Second &lt;/li&gt;    &lt;li&gt;Set First.Alpha to 5 &lt;/li&gt;    &lt;li&gt;Set First.Beta to Second.Gamma (0) &lt;/li&gt;    &lt;li&gt;End initializing First &lt;/li&gt;    &lt;li&gt;Print 0 &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Step 5 is the interesting one here. We know that we need First to be initialized, in order to get First.Alpha, but this thread is &lt;em&gt;already&lt;/em&gt; initializing First (we started in step 3) so we just access First.Alpha and hope that it&amp;#39;s got the right value. As it happens, that variable initializer hasn&amp;#39;t been executed yet. Oops.&lt;/p&gt;  &lt;p&gt;(One subtlety here is that I &lt;em&gt;could &lt;/em&gt;have declared all these variables as constants instead using &amp;quot;const&amp;quot; which would have avoided all these problems.)&lt;/p&gt;  &lt;h1&gt;Back in the real world...&lt;/h1&gt;  &lt;p&gt;Hopefully that example makes it clear why circular dependencies in type initializers are nasty. They&amp;#39;re hard to spot, hard to debug, and hard to test. Pretty much your classic &lt;a href="http://en.wikipedia.org/wiki/Heisenbug"&gt;Heisenbug&lt;/a&gt;, really. It&amp;#39;s important to note that if the program above had &lt;em&gt;happened&lt;/em&gt; to initialize Second first (to access a different variable, for example) we could have ended up with a different result. In particular, it&amp;#39;s easy to get into a situation where running &lt;em&gt;all&lt;/em&gt; your unit tests can cause a failure - but if you run &lt;em&gt;just&lt;/em&gt; the failing test, it passes.&lt;/p&gt;  &lt;p&gt;One way of avoiding all of this is never to use any type initializers for anything, of course. In many cases that&amp;#39;s exactly the right solution - but often there &lt;em&gt;are&lt;/em&gt; natural uses, particularly for well-known values such as &lt;a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.utf8.aspx"&gt;Encoding.Utf8&lt;/a&gt;, &lt;a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.utc.aspx"&gt;TimeZoneInfo.Utc&lt;/a&gt; and the like. Note that in both of those cases they are static &lt;em&gt;properties&lt;/em&gt;, but I would expect them to be backed by static fields. I&amp;#39;m somewhat ambivalent between using public static readonly fields and public static get-only properties - but as we&amp;#39;ll see later, there&amp;#39;s a definite advantage to using properties.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://noda-time.googlecode.com"&gt;Noda Time&lt;/a&gt; has quite a few values like this - partly because so many of its types are immutable. It makes sense to create a single UTC time zone, a single ISO calendar system, a single &amp;quot;pattern&amp;quot; (text formatter/parser) for each of a variety of common cases. In addition to the publicly visible values, there are various static variables used internally, mostly for caching purposes. All of this definitely adds complexity - &lt;em&gt;and&lt;/em&gt; makes it harder to test - but the performance benefits can be significant.&lt;/p&gt;  &lt;p&gt;Unfortunately, a lot of these values end up with fairly natural circular dependencies - as I discovered just recently, where adding a new static field caused all kinds of breakage. I was able to fix the immediate cause, but it left me concerned about the integrity of the code. I&amp;#39;d fixed the one failure I knew about - but what about any others?&lt;/p&gt;  &lt;h1&gt;Testing type initialization&lt;/h1&gt;  &lt;p&gt;One of the biggest issues with type initialization is the order-sensitivity - combined with the way that once a type has been initialized once, that&amp;#39;s it for that AppDomain. As I showed earlier, it&amp;#39;s possible that initializing types in one particular order causes a problem, but a different order won&amp;#39;t.&lt;/p&gt;  &lt;p&gt;I&amp;#39;ve decided that for Noda Time at least, I want to be reasonably sure that type initialization circularity isn&amp;#39;t going to bite me. So I want to validate that no type initializers form cycles, whatever order the types are initialized in. Logically if we can detect a cycle starting with one type, we &lt;em&gt;ought&lt;/em&gt; to be able to detect it starting with any of the other types in that cycle - but I&amp;#39;m sufficiently concerned about weird corner cases that I&amp;#39;d rather just take a brute force approach.&lt;/p&gt;  &lt;p&gt;So, as a rough plan:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Start with an empty set of dependencies &lt;/li&gt;    &lt;li&gt;For each type in the target assembly:      &lt;ul&gt;       &lt;li&gt;Create a new AppDomain &lt;/li&gt;        &lt;li&gt;Load the target assembly into it &lt;/li&gt;        &lt;li&gt;Force the type to be initialized &lt;/li&gt;        &lt;li&gt;Take a stack trace at the start of each type initializer and record any dependencies &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;Look for cycles in the complete set of dependencies &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Note that we&amp;#39;ll never spot a cycle within any single AppDomain, due to the way that type initialization works. We have to put together the results for multiple initialization sequences to try to find a cycle.&lt;/p&gt;  &lt;p&gt;A description of the code would probably be harder to follow than the code itself, but the code is relatively long - I&amp;#39;ve included it at the end of this post to avoid intefering with the narrative flow. For more up-to-date versions in the future, look at the &lt;a href="http://code.google.com/p/noda-time/source/browse/"&gt;Noda Time repository&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;This &lt;em&gt;isn&amp;#39;t&lt;/em&gt; a terribly nice solution, for various reasons:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Creating a new AppDomain and loading assemblies into it &lt;em&gt;from a unit test runner&lt;/em&gt; isn&amp;#39;t as simple as it might be. My code doesn&amp;#39;t currently work with NCrunch; I don&amp;#39;t know how it finds its assemblies yet. When I&amp;#39;ve fixed that, I&amp;#39;m sure other test runners would still be broken. Likewise I&amp;#39;ve had to explicitly filter types to get TeamCity (the continuous integration system Noda Time uses) to work properly. Currently, you&amp;#39;d need to edit the test code to change the filters. (It&amp;#39;s possible that there are better ways of filtering, of course.) &lt;/li&gt;    &lt;li&gt;It relies on each type within the production code which has an &amp;quot;interesting&amp;quot; type initializer to have a line like this:      &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; TypeInitializationChecking = NodaTime.Utility.TypeInitializationChecker.RecordInitializationStart(); &lt;/div&gt;   &lt;/li&gt;    &lt;li&gt;Not only does the previous line need to be added to the production code - it clearly gets executed each time, and takes up heap space per type. It&amp;#39;s only 4 bytes for each type involved, and it does no real work when we&amp;#39;re not testing, but it&amp;#39;s a nuisance anyway. I &lt;em&gt;could&lt;/em&gt; use preprocessor directives to remove the code from non-debug or non-test-targeted builds, but that would look even messier. &lt;/li&gt;    &lt;li&gt;It only picks up cycles which occur when running the version of .NET the tests happen to execute on. Given that there are ordering changes for different versions, I wouldn&amp;#39;t like to claim this is 100% bullet-proof. Likewise if there are only cycles when you&amp;#39;re running in some specific cultures (or other environmental features), it won&amp;#39;t necessarily pick those up. &lt;/li&gt;    &lt;li&gt;I&amp;#39;ve deliberately not tried to make the testing code thread-safe. That&amp;#39;s fine in Noda Time - I don&amp;#39;t have any asynchronous operations or new threads in Noda Time at all - but other code may need to make this more robust. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So with all these caveats, is it still worth it? Absolutely: &lt;strong&gt;it&amp;#39;s already found bugs which have now been fixed&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;In fact, the test didn&amp;#39;t get as far as reporting cycles to start with - it turned out that if you initialized one particular type first, the type initializer would fail with a NullReferenceException. Ouch! Once I&amp;#39;d fixed that, there were still quite a few problems to fix. Somewhat coincidentally, fixing them improved the design too - although the user-visible API didn&amp;#39;t change at all.&lt;/p&gt;  &lt;h1&gt;Fixing type initializer cycles&lt;/h1&gt;  &lt;p&gt;In the past, I&amp;#39;ve occasionally &amp;quot;fixed&amp;quot; type initialization ordering problems by simply moving fields around. The cycles still existed, but I figured out how to make them harmless. I can say now that &lt;em&gt;this approach does not scale, and is more effort than it&amp;#39;s worth&lt;/em&gt;. The code ends up being brittle, hard to think about, and once you&amp;#39;ve got more than a couple of types involved it&amp;#39;s really error-prone, at least for my brain. It&amp;#39;s much better to break the cycle completely. To this end, I&amp;#39;ve ended up using a fairly simple technique to defer initialization of static variables. It&amp;#39;s a poor-man&amp;#39;s &lt;a href="http://msdn.microsoft.com/en-us/library/dd642331.aspx"&gt;Lazy&amp;lt;T&amp;gt;&lt;/a&gt;, to some extent - but I&amp;#39;d rather not have to write Lazy&amp;lt;T&amp;gt; myself, and we&amp;#39;re currently targeting .NET 3.5...&lt;/p&gt;  &lt;p&gt;Basically, instead of exposing a public static readonly field which creates the cycle, you expose a public static readonly property - which returns an internal static readonly field &lt;em&gt;in a nested, private static class&lt;/em&gt;. We still get the nice thread-safe once-only initialization of a type initializer, but the nested type won&amp;#39;t be initialized until it needs to be. (In theory it &lt;em&gt;could&lt;/em&gt; be initialized earlier, but a static constructor would ensure it isn&amp;#39;t.) So long as nothing within the &lt;em&gt;rest&lt;/em&gt; of the type initializer for the containing class uses that property, we avoid the cycle.&lt;/p&gt;  &lt;p&gt;So instead of this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Requires Bar to be initialized - if Bar also requires Foo to be&lt;/span&gt;     &lt;br /&gt;&lt;span class="InlineComment"&gt;// initialized, we have a problem...&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; Foo SimpleFoo = &lt;span class="Keyword"&gt;new&lt;/span&gt; Foo(Bar.Zero); &lt;/div&gt;  &lt;p&gt;We might have:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; Foo SimpleFoo { get { &lt;span class="Statement"&gt;return&lt;/span&gt; Constants.SimpleFoo; } }     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Constants     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; TypeInitializationChecking = NodaTime.Utility.TypeInitializationChecker.RecordInitializationStart();&amp;#160; &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// This requires both Foo and Bar to be initialized, but that&amp;#39;s okay&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// so long as neither of them require Foo.Constants to be initialized.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// (The unit test would spot that.)&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; Foo SimpleFoo = &lt;span class="Keyword"&gt;new&lt;/span&gt; Foo(Bar.Zero);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;I&amp;#39;m currently undecided about whether to include static constructors in these classes to ensure lazy initialization. If the type initializer for Foo triggered the initializer of Foo.Constants, we&amp;#39;d be back to square one... but adding static constructors into each of these nested classes sounds like a bit of a pain. The nested classes should call into the type initialization checking as well, to validate they don&amp;#39;t cause any problems themselves.&lt;/p&gt;  &lt;h1&gt;Conclusion&lt;/h1&gt;  &lt;p&gt;I have to say, part of me really doesn&amp;#39;t like either the testing code or the workaround. Both smack of being &lt;em&gt;clever&lt;/em&gt;, which is never a good thing. It&amp;#39;s definitely worth considering whether you could actually just get rid of the type initializer (or part of it) entirely, avoiding maintaining so much static state. It would be nice to be able to detect these type initializer cycles without running anything, simply using static analysis - I&amp;#39;m going to see whether NDepend could do that when I get a chance. The workaround doesn&amp;#39;t feel as neat as Lazy&amp;lt;T&amp;gt;, which is &lt;em&gt;really&lt;/em&gt; what&amp;#39;s called for here - but I don&amp;#39;t trust myself to implement it correctly and efficiently myself.&lt;/p&gt;  &lt;p&gt;So while both are somewhat hacky, they&amp;#39;re better than the alternative: buggy code. That&amp;#39;s what I&amp;#39;m ashamed to say I had in Noda Time, and I don&amp;#39;t think I&amp;#39;d &lt;em&gt;ever&lt;/em&gt; have spotted all the cycles by inspection. It&amp;#39;s worth a try on your own code - see whether you&amp;#39;ve got problems lurking...&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Appendix: Testing code&lt;/h1&gt;  &lt;p&gt;As promised earlier, here&amp;#39;s the code for the production and test classes.&lt;/p&gt;  &lt;h2&gt;TypeInitializationChecker&lt;/h2&gt;  &lt;p&gt;This is in NodaTime.dll itself.&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; TypeInitializationChecker : MarshalByRefObject     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; List&amp;lt;Dependency&amp;gt; dependencies = &lt;span class="Keyword"&gt;null&lt;/span&gt;;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; MethodInfo EntryMethod = &lt;span class="Keyword"&gt;typeof&lt;/span&gt;(TypeInitializationChecker).GetMethod(&lt;span class="String"&gt;&amp;quot;FindDependencies&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; RecordInitializationStart()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (dependencies == &lt;span class="Keyword"&gt;null&lt;/span&gt;)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; 0;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Type previousType = &lt;span class="Keyword"&gt;null&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; frame &lt;span class="Statement"&gt;in&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; StackTrace().GetFrames())     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; method = frame.GetMethod();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (method == EntryMethod)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;break&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; declaringType = method.DeclaringType;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (method == declaringType.TypeInitializer)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (previousType != &lt;span class="Keyword"&gt;null&lt;/span&gt;)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dependencies.Add(&lt;span class="Keyword"&gt;new&lt;/span&gt; Dependency(declaringType, previousType));     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; previousType = declaringType;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; 0;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// Invoked from the unit tests, this finds the dependency chain for a single type&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// by invoking its type initializer.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Dependency[] FindDependencies(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; name)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dependencies = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;Dependency&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Type type = &lt;span class="Keyword"&gt;typeof&lt;/span&gt;(TypeInitializationChecker).Assembly.GetType(name, &lt;span class="Keyword"&gt;true&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; RuntimeHelpers.RunClassConstructor(type.TypeHandle);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; dependencies.ToArray();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// A simple from/to tuple, which can be marshaled across AppDomains.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Dependency : MarshalByRefObject     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; From { get; &lt;span class="Modifier"&gt;private&lt;/span&gt; set; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; To { get; &lt;span class="Modifier"&gt;private&lt;/span&gt; set; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt; Dependency(Type &lt;span class="Linq"&gt;from&lt;/span&gt;, Type to)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; From = &lt;span class="Linq"&gt;from&lt;/span&gt;.FullName;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; To = to.FullName;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;h2&gt;TypeInitializationTest&lt;/h2&gt;  &lt;p&gt;This is within NodaTime.Test:&lt;/p&gt;  &lt;div class="code"&gt;[TestFixture]    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; TypeInitializationTest     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [Test]     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; BuildInitializerLoops()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Assembly assembly = &lt;span class="Keyword"&gt;typeof&lt;/span&gt;(TypeInitializationChecker).Assembly;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; dependencies = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;TypeInitializationChecker.Dependency&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Test each type in a new AppDomain - we want to see what happens where each type is initialized first.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Note: Namespace prefix check is present to get this to survive in test runners which&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// inject extra types. (Seen with JetBrains.Profiler.Core.Instrumentation.DataOnStack.)&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; type &lt;span class="Statement"&gt;in&lt;/span&gt; assembly.GetTypes().Where(t =&amp;gt; t.FullName.StartsWith(&lt;span class="String"&gt;&amp;quot;NodaTime&amp;quot;&lt;/span&gt;)))     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Note: this won&amp;#39;t be enough to load the assembly in all test runners. In particular, it fails in&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// NCrunch at the moment.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; AppDomainSetup setup = &lt;span class="Keyword"&gt;new&lt;/span&gt; AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory };     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; AppDomain domain = AppDomain.CreateDomain(&lt;span class="String"&gt;&amp;quot;InitializationTest&amp;quot;&lt;/span&gt; + type.Name, AppDomain.CurrentDomain.Evidence, setup);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; helper = (TypeInitializationChecker)domain.CreateInstanceAndUnwrap(assembly.FullName,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;typeof&lt;/span&gt;(TypeInitializationChecker).FullName);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dependencies.AddRange(helper.FindDependencies(type.FullName));     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; lookup = dependencies.ToLookup(d =&amp;gt; d.From, d =&amp;gt; d.To);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// This is less efficient than it might be, but I&amp;#39;m aiming for simplicity: starting at each type&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// which has a dependency, can we make a cycle?&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// See Tarjan&amp;#39;s Algorithm in Wikipedia for ways this could be made more efficient.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// http://en.wikipedia.org/wiki/Tarjan&amp;#39;s_strongly_connected_components_algorithm&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt;&amp;#160;&lt;span class="Linq"&gt;group&lt;/span&gt;&amp;#160;&lt;span class="Statement"&gt;in&lt;/span&gt; lookup)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Stack&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; path = &lt;span class="Keyword"&gt;new&lt;/span&gt; Stack&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CheckForCycles(&lt;span class="Linq"&gt;group&lt;/span&gt;.Key, path, lookup);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; CheckForCycles(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; next, Stack&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; path, ILookup&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; dependencyLookup)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (path.Contains(next))     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Assert.Fail(&lt;span class="String"&gt;&amp;quot;Type initializer cycle: {0}-{1}&amp;quot;&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;.Join(&lt;span class="String"&gt;&amp;quot;-&amp;quot;&lt;/span&gt;, path.Reverse().ToArray()), next);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; path.Push(next);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; candidate &lt;span class="Statement"&gt;in&lt;/span&gt; dependencyLookup[next].Distinct())     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CheckForCycles(candidate, path, dependencyLookup);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; path.Pop();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1808561" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/aF_dVyhKyCg" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Evil+Code/default.aspx">Evil Code</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Noda+Time/default.aspx">Noda Time</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/04/07/type-initializer-circular-dependencies.aspx</feedburner:origLink></item><item><title>Diagnosing weird problems - a Stack Overflow case study</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/CIaupaq9SkE/diagnosing-weird-problems-a-stack-overflow-case-study.aspx</link><pubDate>Fri, 16 Mar 2012 06:31:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1807429</guid><dc:creator>skeet</dc:creator><slash:comments>14</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1807429</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1807429</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/03/16/diagnosing-weird-problems-a-stack-overflow-case-study.aspx#comments</comments><description>&lt;p&gt;Earlier, I came across &lt;a href="http://stackoverflow.com/questions/9728056"&gt;this Stack Overflow question&lt;/a&gt;. I solved it, tweeted it, but then thought it would serve as a useful case study into the mental processes I go through when trying to solve a problem - whether that&amp;#39;s on Stack Overflow, at work, or at home.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s definitely worth reading the original question, but the executive summary is:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;When I compute the checksum/hash of c:\Windows\System32\Calc.exe using various tools and algorithms, those tools all give the same answer for each algorithm. When I try doing the same thing in Java, I get different results. What&amp;#39;s going on?&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now to start with, I&amp;#39;d like to shower a bit of praise on the author:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The post came with a short but utterly complete program to demonstrate the problem &lt;/li&gt;    &lt;li&gt;The comments in the program showed the expected values and the actual values &lt;/li&gt;    &lt;li&gt;The code was mostly pretty clean (clean enough for an SO post anyway) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In short, it had pretty much &lt;a href="http://tinyurl.com/so-hints"&gt;everything I ask for in a question&lt;/a&gt;. Yay! Additionally, the result seemed to be strange. The chances of any one of Java&amp;#39;s hashing algorithms being broken seem pretty slim, but &lt;em&gt;four&lt;/em&gt; of them? Okay, now you&amp;#39;ve got me interested. &lt;/p&gt;  &lt;h3&gt;Reproducing the problem&lt;/h3&gt;  &lt;p&gt;Unless I can spot the error immediately, I usually try to reproduce the problem in a Stack Overflow post with a short but complete program. In this case, the program was already provided, so it was just a matter of copy/paste/compile/run. This one had the additional tweak that it was comparing the results of Java with the results of other tools, so I had to get hold of an MD5 sum tool first. (I chose to start with MD5 for no particular reason.) I happened to pick &lt;a href="http://www.pc-tools.net/win32/md5sums/"&gt;this one&lt;/a&gt;, but it didn&amp;#39;t really seem it would make much difference. (As it happens, that was an incorrect assumption, but hey...)&lt;/p&gt;  &lt;p&gt;I ran md5sums on c:\Windows\System32\calc.exe, and got the same result as the poster. Handy.&lt;/p&gt;  &lt;p&gt;I then ran the Java code, and again got the same result as the poster: step complete, we have a discrepancy between at least one tool (and MD5 isn&amp;#39;t that hard to get right) and Java.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Looking for obvious problems&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The code has four main areas:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Reading a file &lt;/li&gt;    &lt;li&gt;Updating digests &lt;/li&gt;    &lt;li&gt;Converting bytes to hex &lt;/li&gt;    &lt;li&gt;Storing and displaying results &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Of these, all of the first three have common and fairly simple error modes. For example:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Failure to use the return value from InputStream.read() &lt;/li&gt;    &lt;li&gt;Failure to update the digests using only the relevant portion of the data buffer &lt;/li&gt;    &lt;li&gt;Failure to cope with Java&amp;#39;s signed bytes &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The code for storing and displaying results seemed solid enough to ignore to start with, and brief inspection suggested that the first two failure modes had been avoided. While the hex code didn&amp;#39;t have any &lt;em&gt;obvious&lt;/em&gt; problems either, it made sense to check it. I simply printed the result of hard-coding the &amp;quot;known good&amp;quot; CRC-32 value:&lt;/p&gt;  &lt;div class="code"&gt;System.out.println(toHex(&lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;#160;&lt;span class="Type"&gt;byte&lt;/span&gt;[] {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; (&lt;span class="Type"&gt;byte&lt;/span&gt;) 0x8D, (&lt;span class="Type"&gt;byte&lt;/span&gt;) 0x8F, (&lt;span class="Type"&gt;byte&lt;/span&gt;) 0x5F, (&lt;span class="Type"&gt;byte&lt;/span&gt;) 0x8E     &lt;br /&gt;&amp;#160; })); &lt;/div&gt;  &lt;p&gt;That produced the right result, so I ruled out that part of the code too. Even if it had errors in some cases, we know it&amp;#39;s capable of producing the right string for one of the values we know we &lt;em&gt;should&lt;/em&gt; be returning, so it can&amp;#39;t be getting that value.&lt;/p&gt;  &lt;h3&gt;Initial checks around the file&lt;/h3&gt;  &lt;p&gt;I&amp;#39;m always suspicious of stream-handling code - or rather, I know how easily it can hide subtle bugs. Even though it &lt;em&gt;looked&lt;/em&gt; okay, I thought I&amp;#39;d check - so I added a simple total to the code so I could see how many bytes had been hashed. I also removed all the hash algorithms other than MD5, just for simplicity:&lt;/p&gt;  &lt;div class="code"&gt;MessageDigest md5 = MessageDigest.getInstance(&lt;span class="String"&gt;&amp;quot;MD5&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;FileInputStream fis = &lt;span class="Keyword"&gt;new&lt;/span&gt; FileInputStream(file);     &lt;br /&gt;&lt;span class="Type"&gt;byte&lt;/span&gt; data[] = &lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;#160;&lt;span class="Type"&gt;byte&lt;/span&gt;[size];     &lt;br /&gt;&lt;span class="Type"&gt;int&lt;/span&gt; len = 0;     &lt;br /&gt;&lt;span class="Type"&gt;int&lt;/span&gt; total = 0;     &lt;br /&gt;&lt;span class="Statement"&gt;while&lt;/span&gt; ((len = fis.read(data)) != -1) {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; md5.update(data, 0, len);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; total += len;     &lt;br /&gt;}     &lt;br /&gt;fis.close();     &lt;br /&gt;System.out.println(&lt;span class="String"&gt;&amp;quot;Total bytes read: &amp;quot;&lt;/span&gt; + total);     &lt;br /&gt;    &lt;br /&gt;results.put(md5.getAlgorithm(), toHex(md5.digest())); &lt;/div&gt;  &lt;p&gt;It&amp;#39;s worth noting that I &lt;em&gt;haven&amp;#39;t&lt;/em&gt; tried to fix up bits of the code which I know I would change if I were actually doing a code review:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The stream isn&amp;#39;t being closed in a finally block, so we&amp;#39;ll have a dangling resource (until GC) if an IOException is thrown &lt;/li&gt;    &lt;li&gt;The initial value of len is never read, and can be removed &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Neither of these matters in terms of the problem at hand, and closing the file &amp;quot;properly&amp;quot; would make the sample code more complicated. (For the sake of just a short sample program, I&amp;#39;d be tempted to remove it entirely.)&lt;/p&gt;  &lt;p&gt;The result showed the number of bytes being read as the command prompt did when I ran &amp;quot;dir c:\Windows\System32\Calc.exe&amp;quot; - so again, everything looks like it&amp;#39;s okay.&lt;/p&gt;  &lt;h3&gt;Desperate times call for stupid measures&lt;/h3&gt;  &lt;p&gt;Just on a whim, I decided to copy Calc.exe to a local folder (the current directory) and retry. After all, accessing a file in a system folder &lt;em&gt;might&lt;/em&gt; have some odd notions applied to it. It&amp;#39;s hard to work out what, but... there&amp;#39;s nothing to lose just by trying a simple test. If it can rule &lt;em&gt;anything&lt;/em&gt; out, and you&amp;#39;ve got no better ideas, you might as well try even the daftest idea.&lt;/p&gt;  &lt;p&gt;I modified the source code to use the freshly-copied file, and it gave the same result. Hmm.&lt;/p&gt;  &lt;p&gt;I then reran md5sums on the copied file... and it gave &lt;em&gt;the same result as Java&lt;/em&gt;. In other words, running &amp;quot;md5sums c:\Windows\System32\Calc.exe&amp;quot; gave one result, but &amp;quot;md5sums CopyOfCalc.exe&amp;quot; gave a different result. At this point we&amp;#39;ve moved from &lt;em&gt;Java&lt;/em&gt; looking like it&amp;#39;s behaving weirdly to &lt;em&gt;md5sums&lt;/em&gt; looking suspicious.&lt;/p&gt;  &lt;h3&gt;Proving the root cause&lt;/h3&gt;  &lt;p&gt;At this point we&amp;#39;re &lt;em&gt;sort of&lt;/em&gt; done - we&amp;#39;ve basically proved that the Java code produces the right hash for whatever data it&amp;#39;s given, but we&amp;#39;re left with the question of what&amp;#39;s happening on the file system. I had a hunch that it might be something to do with x86 vs x64 code (all of this was running on a 64-bit version of Windows 7) - so how do we test that assumption?&lt;/p&gt;  &lt;p&gt;I don&amp;#39;t know if there&amp;#39;s a simple way of running an x86 version of the JVM, but I &lt;em&gt;do&lt;/em&gt; know how to switch .NET code between x86 and x64 - you can do that for an assembly at build time. C# also makes the hashing and hex conversion simple, so I was able to knock up a very small app to show the problem:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;     &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.IO;     &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Security.Cryptography;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Test     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Namespace"&gt;using&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; md5 = MD5.Create())     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; path = &lt;span class="String"&gt;&amp;quot;c:/Windows/System32/Calc.exe&amp;quot;&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; bytes = md5.ComputeHash(File.ReadAllBytes(path));     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(BitConverter.ToString(bytes));     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;(For a larger file I&amp;#39;d have used File.OpenRead instead, but then I&amp;#39;d have wanted to close the stream afterwards. Somehow it wasn&amp;#39;t worth correcting the &lt;em&gt;existing&lt;/em&gt; possible handle leak in the Java code, but I didn&amp;#39;t want to write leaky code myself. So instead I&amp;#39;ve got code which reads the whole file into memory unnecessarily... &amp;lt;sigh&amp;gt;)&lt;/p&gt;  &lt;p&gt;You can choose the architecture to build against (usually AnyCPU, x86 or x64 - though it&amp;#39;s interesting to see that &amp;quot;arm&amp;quot; is also an option under .NET 4.5, for obvious reasons) either from Visual Studio or using the &amp;quot;/platform&amp;quot; command line option. This doesn&amp;#39;t change the IL emitted (as far as I&amp;#39;m aware) but it&amp;#39;s used for interop with native code - and in the case of executables, it also determines the version of the CLR which is used.&lt;/p&gt;  &lt;p&gt;Building and running in x86 mode gave the same answer as the original &amp;quot;assumed to be good&amp;quot; tools; building and running in x64 mode gave the same answer as Java.&lt;/p&gt;  &lt;h3&gt;Explaining the root cause&lt;/h3&gt;  &lt;p&gt;At this point we&amp;#39;ve proved that the file system gives different results depending on whether you access it from a 64-bit process or a 32-bit process. The &lt;em&gt;final&lt;/em&gt; piece of the puzzle was to find some something to explain why that happens. With all the evidence about what&amp;#39;s happening, it was now easy to search for more information, and I found &lt;a href="http://www.samlogic.net/articles/32-64-bit-windows-folder-x86-syswow64.htm"&gt;this article&lt;/a&gt; giving satisfactory details. Basically, there are two different copies of the system executables on a 64 bit system: x86 ones which run under the 32-bit emulator, and x64 ones. They&amp;#39;re actually in different directories, but when a process opens a file in \Windows\System32, the copy which matches the architecture of the process is used. It&amp;#39;s almost as if the \Windows\System32 directory is a symlink which changes target depending on the current process.&lt;/p&gt;  &lt;p&gt;A Stack Overflow comment on my answer gave a final nugget that this is called the &amp;quot;File System Redirector&amp;quot;.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;Debugging sessions often feel a bit like this - particularly if you&amp;#39;re like me, and only resort to &lt;em&gt;real&lt;/em&gt; debugging after unit testing has failed. It&amp;#39;s a matter of looking under all kinds of rocks, trying anything and everything, but keeping track of everything you try. At the end of process you should be able to explain &lt;em&gt;every&lt;/em&gt; result you&amp;#39;ve seen, in an ideal world. (You may not be able to give evidence of the actual chain of events, but you should be able to construct a plausible chain of events which concurs with your theory.)&lt;/p&gt;  &lt;p&gt;Be aware of areas which can &lt;em&gt;often&lt;/em&gt; lead to problems, and check those first, gradually reducing the scope of &amp;quot;stuff you don&amp;#39;t understand&amp;quot; to a manageable level, until it disappears completely.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1807429" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/CIaupaq9SkE" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/General/default.aspx">General</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/03/16/diagnosing-weird-problems-a-stack-overflow-case-study.aspx</feedburner:origLink></item><item><title>Eduasync 20: Changes between the VS11 Preview and the Visual Studio 11 Beta</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/RJXvEh-Qhn4/eduasync-20-changes-between-the-vs11-preview-and-the-visual-studio-11-beta.aspx</link><pubDate>Tue, 06 Mar 2012 19:54:54 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1807031</guid><dc:creator>skeet</dc:creator><slash:comments>8</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1807031</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1807031</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/03/06/eduasync-20-changes-between-the-vs11-preview-and-the-visual-studio-11-beta.aspx#comments</comments><description>&lt;p&gt;A while I ago I &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2012/01/12/eduasync-part-18-changes-between-the-async-ctp-and-the-visual-studio-11-preview.aspx"&gt;blogged about&lt;/a&gt; what had changed under the hood of async between the CTP and the VS11 Preview. Well, now that the VS11 Beta is out, it&amp;#39;s time to do it all again...&lt;/p&gt;  &lt;p&gt;Note that the code in this post &lt;em&gt;is &lt;/em&gt;in the &lt;a href="http://eduasync.googlecode.com"&gt;Eduasync codebase&lt;/a&gt;, under a different solution (Eduasync VS11.sln). Many of the old existing projects won&amp;#39;t compile with VS11 beta, but I&amp;#39;d rather leave them as they are for posterity, showing the evolution of the feature.&lt;/p&gt;  &lt;p&gt;Stephen Toub has an &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2012/02/29/10274035.aspx"&gt;excellent blog post&lt;/a&gt; covering some of this, so while I&amp;#39;ll &lt;em&gt;mention&lt;/em&gt; things he&amp;#39;s covered, I won&amp;#39;t go into much detail about them. Let&amp;#39;s start off there though...&lt;/p&gt;  &lt;p&gt;(EDIT: Stephen has also mailed me with some corrections, which I&amp;#39;ve edited in - mostly without indication, as the post has been up for less than seven hours, and it&amp;#39;ll make for a better reading experience.)&lt;/p&gt;  &lt;h2&gt;Awaiter pattern changes&lt;/h2&gt;  &lt;p&gt;The awaiter pattern is now not &lt;em&gt;just&lt;/em&gt; a pattern. The IsCompleted property and GetResult method are still &amp;quot;loose&amp;quot; but &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.inotifycompletion.oncompleted(v=vs.110).aspx"&gt;OnCompleted&lt;/a&gt; is now part of an interface: &lt;a href="http://msdn.microsoft.com/en-us/library/hh472348(v=vs.110).aspx"&gt;INotifyCompletion&lt;/a&gt;. Awaiters &lt;em&gt;have&lt;/em&gt; to implement INotifyCompleted, but may &lt;em&gt;also&lt;/em&gt; implement &lt;a href="http://msdn.microsoft.com/en-us/library/hh472362(v=vs.110).aspx"&gt;ICriticalNotifyCompletion&lt;/a&gt; and its &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.icriticalnotifycompletion.unsafeoncompleted(v=vs.110).aspx"&gt;UnsafeOnCompleted&lt;/a&gt; method.&lt;/p&gt;  &lt;p&gt;The OnCompleted method is just as it was before, and needs to flow the execuction context; the UnsafeOnCompleted method is simpler, as it &lt;em&gt;doesn&amp;#39;t&lt;/em&gt; need to flow the execution context. All of this only matters if you&amp;#39;re implementing your own awaiters, of course. (More details in Stephen&amp;#39;s blog post. I&amp;#39;ve found this area somewhat confusing, so please do read his post carefully!)&lt;/p&gt;  &lt;h2&gt;Skeleton method changes&lt;/h2&gt;  &lt;p&gt;Just as I have previously, I&amp;#39;m using the (entirely unofficial) term &amp;quot;skeleton method&amp;quot; to mean the very short method created by the compiler with the same signature as an async method: this is the entry point to the async method, effectively, which creates and starts the state machine containing all the &lt;em&gt;real&lt;/em&gt; logic.&lt;/p&gt;  &lt;p&gt;There are two changes I&amp;#39;ve noticed in the skeleton method. Firstly, for some reason the state machine state numbers have changed. Whereas previously a state number of 0 meant &amp;quot;initial or running&amp;quot;, positive values meant &amp;quot;between calls, or navigating back to the await expression&amp;quot; and -1 meant &amp;quot;finished&amp;quot;, now -1 means &amp;quot;initial or running&amp;quot;, non-negative means &amp;quot;between calls, or navigating back to await expression&amp;quot; and -2 means &amp;quot;finished&amp;quot;. It&amp;#39;s not clear why this change has been made, given that it requires an extra assignment at the start of every skeleton method (to set the state to -1).&lt;/p&gt;  &lt;p&gt;More importantly, the skeleton method no longer calls MoveNext directly on the state machine that it&amp;#39;s built. Instead, it calls &lt;a href="http://msdn.microsoft.com/en-us/library/hh472313(v=vs.110).aspx"&gt;Start&amp;lt;TStateMachine&amp;gt;&lt;/a&gt; on the &lt;a href="http://msdn.microsoft.com/en-us/library/hh138506(v=vs.110).aspx"&gt;AsyncTaskMethodBuilder&amp;lt;T&amp;gt;&lt;/a&gt; (or whichever method builder it&amp;#39;s using). It passes the state machine by reference (presumably for efficiency), and TStateMachine is constrained to implement the now-public-and-in-mscorlib &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.iasyncstatemachine(v=vs.110).aspx"&gt;IAsyncStateMachine&lt;/a&gt; interface. I&amp;#39;ll come back to the relationship between the state machine and the builder later on.&lt;/p&gt;  &lt;h2&gt;Task caching&lt;/h2&gt;  &lt;p&gt;(Code is in project 30: &lt;a href="http://code.google.com/p/eduasync/source/browse/#hg%2Fsrc%2FTaskCaching"&gt;TaskCaching&lt;/a&gt;)&lt;/p&gt;  &lt;p&gt;It&amp;#39;s possible for an async method to complete entirely synchronously. In this situation, the result is known before the method returns, and the task returned by the method is already in the RanToCompletionState. If two tasks have already run to completion with the same value, they can be (apparently) regarded as equivalent... so the beta now caches a task in this situation, for some types and values. (Apparently the preview cached too, but I hadn&amp;#39;t noticed, and the beta caches more.) According to my experiments and some comments:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;For int, tasks with values -1 to 8 inclusive are cached &lt;/li&gt;    &lt;li&gt;For bool, both values (true and false)&lt;/li&gt;    &lt;li&gt;For char, byte, sbyte, short, ushort, uint, long, ulong, IntPtr and UIntPtr tasks with value 0 (or &amp;#39;\0&amp;#39;) are cached &lt;/li&gt;    &lt;li&gt;For reference types, null is cached&lt;/li&gt;    &lt;li&gt;For other types, no tasks are cached&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;EDIT: After they&amp;#39;ve completed, tasks are normally immutable &lt;em&gt;except for disposal&lt;/em&gt; - the cached tasks are tweaked slightly to make disposal a no-op. &lt;/p&gt;  &lt;h2&gt;State machine interface changes&lt;/h2&gt;  &lt;p&gt;In the VS11 preview release, each state machine implemented an interface, but that interface was internal to the generated assembly, and contained a single method (SetMoveNextDelegate). It&amp;#39;s now a public interface with two methods:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.iasyncstatemachine.movenext(v=vs.110).aspx"&gt;MoveNext&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.iasyncstatemachine.setstatemachine(v=vs.110).aspx"&gt;SetStateMachine&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Personally I&amp;#39;m not keen on the naming of &amp;quot;MoveNext&amp;quot; - I can&amp;#39;t help but feel that if we didn&amp;#39;t have the &amp;quot;naming baggage&amp;quot; of IEnumerator and the fact that at least early on, the code generator was very similar to that used for iterator blocks, we&amp;#39;d have something different. (It &lt;em&gt;is&lt;/em&gt; moving to the next state of the state machine, but it still doesn&amp;#39;t quite feel right.) I&amp;#39;d favour something like &amp;quot;ContinueExecution&amp;quot;. However, it doesn&amp;#39;t matter - it obviously does what you&amp;#39;d expect, and you&amp;#39;re not going to be calling this yourself.&lt;/p&gt;  &lt;p&gt;SetStateMachine is a stranger beast. The documentation states:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Configures the state machine with a heap-allocated replica.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;... which says almost nothing, really. The implementation is always simple, just like SetMoveNextDelegate was, although this time it delegates to the builder for the real work (a common theme, as we&amp;#39;ll see):&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ValueType"&gt;void&lt;/span&gt; IAsyncStateMachine.SetStateMachine(IAsyncStateMachine param0)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.&amp;lt;&amp;gt;t__builder.SetStateMachine(param0);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Now &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.asynctaskmethodbuilder.setstatemachine(v=vs.110).aspx"&gt;AsyncTaskMethodBuilder.SetStateMachine&lt;/a&gt; is also documented pretty sparsely:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Associates the builder with the specified state machine.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Again, no real help. However, we&amp;#39;ll see that it&amp;#39;s the &lt;em&gt;builder&lt;/em&gt; which is responsible for calling OnContinue now, and as it can call MoveNext on an IStateMachine, it makes sense to tell it which state machine it&amp;#39;s associated with... but can&amp;#39;t it do that directly?&lt;/p&gt;  &lt;p&gt;Well, not quite. The problem (as I understand it) is around when boxing occurs. We initially create the state machine on the stack, and it contains the builder. (Both are structs.) That&amp;#39;s fine until we need a continuation, but then we&amp;#39;ve got to be able to get back to the current state later, after the current stack frame has been blown away. So we need to box the state machine. That will create a &lt;em&gt;copy&lt;/em&gt; of the current builder (within the box). We need the builder within the boxed state machine to contain a reference to the same box. So the order has to be:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Box the state machine &lt;/li&gt;    &lt;li&gt;Tell the state machine about the boxed reference &lt;/li&gt;    &lt;li&gt;The state machine tells its nested builder about the boxed reference &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Back when the state machine was in charge of the boxing, this went via the delegate: the act of creating the box was implicit when creating the delegate, and then casting the delegate target to the interface type allowed a reference to the newly-created delegate to be set within the copy. This is similar, but using the builder instead. It&amp;#39;s hard to follow, but of course it&amp;#39;s not going to matter.&lt;/p&gt;  &lt;h2&gt;State machine field changes&lt;/h2&gt;  &lt;p&gt;There are various kinds of fields in the state machine:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Those corresponding with local variables and parameters in the async method &lt;/li&gt;    &lt;li&gt;The state &lt;/li&gt;    &lt;li&gt;The field(s) associated with awaiters &lt;/li&gt;    &lt;li&gt;(In the preview/beta) The field associated with the &amp;quot;current execution stack&amp;quot; at the point of an await expression &lt;/li&gt;    &lt;li&gt;(In the CTP) An unused &amp;quot;disposing&amp;quot; field &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Of these, I believe only the awaiters have actually changed, but before we talk about that, let&amp;#39;s revisit local variables.&lt;/p&gt;  &lt;h3&gt;Local variable hoisting&lt;/h3&gt;  &lt;p&gt;I&amp;#39;ve just noticed that the local variables are only hoisted to fields when its scope contains an await expressions, but in that case &lt;em&gt;all&lt;/em&gt; local variables of that scope are hoisted, whether or not they&amp;#39;re used &amp;quot;across&amp;quot; awaits. It would be possible to hoist only those which need to be maintained between executions, but then you wouldn&amp;#39;t be able to see the others when debugging, which would be somewhat confusing. Likewise local variables of the same type which are never propagated across the same await &lt;em&gt;could&lt;/em&gt; be aliased. For example, consider this async method:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; M(Random rng)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; x = rng.Next(1000);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; y = x + rng.Next(1000);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;await&lt;/span&gt; Task.Yield();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; z = y + rng.Next(1000);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;await&lt;/span&gt; Task.Yield();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; z;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;If the compiler could be confident you didn&amp;#39;t need to debug through this code, it &lt;em&gt;could&lt;/em&gt; make do with one field of type &amp;quot;Random&amp;quot; and one field of type &amp;quot;int&amp;quot; - x can be a completely local variable in MoveNext (it&amp;#39;s not used between two awaits) and y and z can be aliased (we never need the value of y after we&amp;#39;ve first written to z).&lt;/p&gt;  &lt;p&gt;Local variable aliasing probably isn&amp;#39;t particularly useful for &amp;quot;normal&amp;quot; methods as the JIT may be able to do it (so long as you don&amp;#39;t have a debugger attached, potentially) but in this case we expect the state machine to be boxed at some point, so potentially &lt;em&gt;does&lt;/em&gt; make a difference (while the stack is typically reasonably small, you could have a &lt;em&gt;lot&lt;/em&gt; of outstanding async methods in some scenarios). Maybe in a future release, the C# compiler could have an aggressive optimization mode around this, to be turned on explicitly. (I don&amp;#39;t think it should be&amp;#160; a particularly high priority, mind you.)&lt;/p&gt;  &lt;h3&gt;Awaiter fields&lt;/h3&gt;  &lt;p&gt;(Code is in project 31, &lt;a href="http://code.google.com/p/eduasync/source/browse/#hg%2Fsrc%2FAwaiterFields"&gt;AwaiterFields&lt;/a&gt;.)&lt;/p&gt;  &lt;p&gt;Awaiter fields have changed a bit over the course of async&amp;#39;s history.&lt;/p&gt;  &lt;p&gt;In the CTPs (all of them, I believe) each await expression had its own awaiter field in the state machine, with a type corresponding to the declared awaiter type from the awaitable. (Remember that the awaitable is the thing you await, such as a task, and the awaiter is what you get back from calling GetAwaiter on the awaitable).&lt;/p&gt;  &lt;p&gt;In the VS11 Preview, there was always a single awaiter field of type object. From what I saw, it was usually populated with a single-element array containing an awaiter. For value type awaiters (i.e. where the awaiter is a struct) this is somewhat similar to boxing, but maintaining strong typing, so calls to IsCompleted etc can still be made. It&amp;#39;s possible that reference type awaiters were stored without the array creation, as it would serve no purpose. (I don&amp;#39;t have any machines with just the preview installed to verify this.)&lt;/p&gt;  &lt;p&gt;In the Beta, we have a mixture. If there are any reference type awaiters, they all end up being stored in a single field of type object, which is then cast back to the actual type when required. (Don&amp;#39;t forget that only one awaiter can be &amp;quot;active&amp;quot; at a time, which makes this possible.) This includes awaiters of an interface type - it&amp;#39;s only the &lt;em&gt;compile-time&lt;/em&gt; type declared as the return type of the GetAwaiter method of the awaitable which is important.&lt;/p&gt;  &lt;p&gt;If any of the awaiter types are value types, each of these types gets its own field. So there might be a TaskAwaiter&amp;lt;int&amp;gt; field and a TaskAwaiter&amp;lt;string&amp;gt; field, for example. However, there can still be &amp;quot;sharing&amp;quot; going on: if there are multiple await expressions all of the same value type awaiter, they will all share a single field. (This all feels a &lt;em&gt;little&lt;/em&gt; like the JITting of generics, but it&amp;#39;s somewhat coincidental.)&lt;/p&gt;  &lt;h2&gt;MoveNext method changes&lt;/h2&gt;  &lt;p&gt;(Code is in project 32, BetaStateMachine)&lt;/p&gt;  &lt;p&gt;As I&amp;#39;ve mentioned earlier, the builder is now responsible for a lot more of the work than it was in earlier versions. The majority of the code remains the same as far as I can tell, in terms of handling branching, evaluating expressions with multiple await expressions and so on.&amp;#160; The code in the source repository shows what the complete state machine looks like, but for the sake of clarity, I&amp;#39;ll just focus on a single snippet. If we have an await expression like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;await&lt;/span&gt; x; &lt;/div&gt;  &lt;p&gt;then the state machine code in the VS11 Preview would look something like this:&lt;/p&gt;  &lt;div class="code"&gt;localTaskAwaiter = x.GetAwaiter();    &lt;br /&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (localTaskAwaiter.IsCompleted)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;goto&lt;/span&gt; AwaitCompleted;     &lt;br /&gt;}     &lt;br /&gt;&lt;span class="Keyword"&gt;this&lt;/span&gt;.state = 1;     &lt;br /&gt;TaskAwaiter[] awaiterArray = { localTaskAwaiter };     &lt;br /&gt;&lt;span class="Keyword"&gt;this&lt;/span&gt;.awaiter = awaiterArray;     &lt;br /&gt;Action continuation = &lt;span class="Keyword"&gt;this&lt;/span&gt;.MoveNextDelegate;     &lt;br /&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (continuation == &lt;span class="Keyword"&gt;null&lt;/span&gt;)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; task = &lt;span class="Keyword"&gt;this&lt;/span&gt;.builder.Task;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; continuation = MoveNext;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ((IStateMachine) continuation.Target).SetMoveNextDelegate(continuation);     &lt;br /&gt;}     &lt;br /&gt;awaiterArray[0].OnCompleted(continuation);     &lt;br /&gt;...     &lt;br /&gt;&lt;span class="Statement"&gt;return&lt;/span&gt;; &lt;/div&gt;  &lt;p&gt;(That&amp;#39;s just setting up the await, of course - there&amp;#39;s then the bit where the result is fetched, but that&amp;#39;s less interesting. There&amp;#39;s also the matter of doFinallyBodies.)&lt;/p&gt;  &lt;p&gt;In the VS11 Beta, it&amp;#39;s something this instead (for an awaiter type &amp;quot;AwaiterType&amp;quot; which implements ICriticalNotifyCompletion, in a state machine of type ThisStateMachine).&lt;/p&gt;  &lt;div class="code"&gt;localAwaiter = x.GetAwaiter();    &lt;br /&gt;&lt;span class="Statement"&gt;if&lt;/span&gt; (!localAwaiter.IsCompleted)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; state = 0;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; awaiterField = localAwaiter;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; builder.AwaitUnsafeOnCompleted&amp;lt;AwaiterType, ThisStateMachine&amp;gt;(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; localAwaiter, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;this&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; doFinallyBodies = &lt;span class="Keyword"&gt;false&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;If the awaiter type only implements INotifyCompletion, it calls &lt;a href="http://msdn.microsoft.com/en-us/library/hh472321(v=vs.110).aspx"&gt;AwaitOnCompleted&lt;/a&gt; instead. Note how the calls are generic (but both type variables are constrained to implement appropriate interfaces) which avoids boxing.&lt;/p&gt;  &lt;p&gt;The call to the builder will call &lt;em&gt;back&lt;/em&gt; to the state machine&amp;#39;s SetStateMachine method if this is the first awaiter that hasn&amp;#39;t already completed within this execution of the async method. So that handles the section which checked for the continuation being null in the first block of code. Most of the rest of the change is explained by the difference in awaiter types, and obviously AwaitOnCompleted/AwaitUnsafeOnCompleted &lt;em&gt;also&lt;/em&gt; ends up calling into OnCompleted on the awaiter itself.&lt;/p&gt;  &lt;h2&gt;Mutable value type awaiters&lt;/h2&gt;  &lt;p&gt;(Code is in project 32, &lt;a href="http://code.google.com/p/eduasync/source/browse/#hg%2Fsrc%2FMutableAwaiters"&gt;MutableAwaiters&lt;/a&gt;)&lt;/p&gt;  &lt;p&gt;One subtle difference which &lt;em&gt;really&lt;/em&gt; shouldn&amp;#39;t hurt people but is fun to explore is what happens if you have an awaiter which is a mutable value type. Due to the way awaiters were carefully handled pre-beta, mutations which were conducted as part of OnCompleted would still be visible in GetResult. That&amp;#39;s &lt;em&gt;not&lt;/em&gt; the case in the beta (as Stephen mentions in his blog post). Mind you, it doesn&amp;#39;t mean that &lt;em&gt;all&lt;/em&gt; mutations will be ignored... just ones in OnCompleted. A mutation from IsCompleted is still visible, as shown here:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; MutableAwaiter : INotifyCompletion     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; message;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; MutableAwaiter(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; message)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.message = message;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;bool&lt;/span&gt; IsCompleted     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; get     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; message = &lt;span class="String"&gt;&amp;quot;Set in IsCompleted&amp;quot;&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;false&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; OnCompleted(Action action)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; message = &lt;span class="String"&gt;&amp;quot;Set in OnCompleted&amp;quot;&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Ick! Completes inline. Never mind, it&amp;#39;s only a demo...&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; action();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; GetResult()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; message;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;What would you expect to be returned from this awaiter? You can verify that all three members are called... but &amp;quot;Set in IsCompleted&amp;quot; is returned. That&amp;#39;s because IsCompleted is called &lt;em&gt;before&lt;/em&gt; the awaiter value is copied into a field within the state machine. Even though the state machine passes the awaiter by reference, it&amp;#39;s passing the &lt;em&gt;local&lt;/em&gt; variable, which is of course a separate variable from the field.&lt;/p&gt;  &lt;p&gt;I&amp;#39;m &lt;em&gt;absolutely not&lt;/em&gt; suggesting that you should rely on any of this behaviour. If you really need to be able to mutate your awaiter, make it a reference type.&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;The main changes in the Beta are around the interactions between the AsyncTaskMethodBuilder (et al) and the state machine, including the new interfaces for awaiters. There&amp;#39;s been quite a bit of optimization, although I still see room for a bit more:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;When there&amp;#39;s only a single kind of reference type awaiter, the field for storing it could be of that type rather than of type object, removing the need for an execution-time cast &lt;/li&gt;    &lt;li&gt;The &amp;quot;stack&amp;quot; variable could be removed in some cases, and made into a specific type in many others &lt;/li&gt;    &lt;li&gt;With appropriate optimization flags, local variables which aren&amp;#39;t used await expressions could stay local to the state machine instead of being hoisted, and hoisted variables could be aliased in some cases. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;One thing which concerns me slightly is how the C# language specification is going to change - the addition of the new interfaces is definitely going to mean more complexity from this previously &amp;quot;tidy&amp;quot; feature. I&amp;#39;m sure it&amp;#39;s worth it for the sake of efficiency and the like, but part of me sighs at every added tweak.&lt;/p&gt;  &lt;p&gt;So, is this now close to the finished version of async? Only time will tell. I haven&amp;#39;t checked whether dynamic awaitables have finally been introduced... if they have, I&amp;#39;ll put that in the next post.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1807031" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/RJXvEh-Qhn4" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/03/06/eduasync-20-changes-between-the-vs11-preview-and-the-visual-studio-11-beta.aspx</feedburner:origLink></item><item><title>Subtleties in API design - member placement</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/mW6QsW6GpVc/subtleties-in-api-design-member-placement.aspx</link><pubDate>Wed, 29 Feb 2012 17:27:25 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1806600</guid><dc:creator>skeet</dc:creator><slash:comments>38</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1806600</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1806600</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/02/29/subtleties-in-api-design-member-placement.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://noda-time.googlecode.com"&gt;Noda Time&lt;/a&gt; is nearing v1.0, which means I&amp;#39;m spending more time writing documentation than code. It also means reviewing the APIs we&amp;#39;ve got with a critical eye - whether that&amp;#39;s removing extraneous members, adding useful ones, or moving things around. (In particular, writing documentation often suggests where a change would make calling code read more naturally.)&lt;/p&gt;  &lt;p&gt;This post is about one particular section of the API, and the choices available. Although I &lt;em&gt;do&lt;/em&gt; go into some detail around the specific calls involved, that&amp;#39;s just for context... the underlying choices are ones which could be faced when designing any API. I&amp;#39;ve rarely spent as much time thinking about API decisions as I have with Noda Time, so hopefully this will prove interesting to you even if you really don&amp;#39;t care about Noda Time itself as a project.&lt;/p&gt;  &lt;h1&gt;Introduction: time zones, local date/times and zoned date/times - oh my!&lt;/h1&gt;  &lt;p&gt;(Okay, so that&amp;#39;s not quite as snappy as &lt;a href="http://youtu.be/peh61wd-53w?t=42s"&gt;the Judy Garland version&lt;/a&gt;, but hey...)&lt;/p&gt;  &lt;p&gt;The area of API we&amp;#39;re going to focus on is time zones, and converting between &amp;quot;local&amp;quot; date/time values and &amp;quot;zoned&amp;quot; ones. The three types involved are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;LocalDateTime&lt;/strong&gt;: a &amp;quot;local&amp;quot; date and time, with no specific time zone. So, something like &amp;quot;7:30 in the evening on February 27th 2012&amp;quot;. This means different instants in time in different time zones, of course: if you&amp;#39;re arranging a meeting, it&amp;#39;s good enough when the attendees are in the same time zone, but not good enough if you&amp;#39;re meeting with someone on the other side of the world. (A LocalDateTime also has an associated calendar system, but I&amp;#39;m not going to talk about that much in this post.) &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;DateTimeZone&lt;/strong&gt;: a time zone. At its core, this maps &lt;em&gt;any&lt;/em&gt; &amp;quot;instant&amp;quot; in time to an &lt;em&gt;offset&lt;/em&gt; - the difference between UTC and local time in that time zone. The offset changes over time, typically (but not always) due to daylight saving changes. &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;ZonedDateTime&lt;/strong&gt;: a date and time in a particular time zone, with an offset from UTC to avoid ambiguity in some cases (and for efficiency). This identifies a specific instant in time (simply by subtracting the offset from the local date/time). Conceptually this is equivalent to just maintaining the &amp;quot;instant&amp;quot; value, the time zone, and the calendar system - but it&amp;#39;s generally cleaner to think of it as a &amp;quot;local&amp;quot; value with an offset from UTC. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;If those brief descriptions don&amp;#39;t make sense for you at the moment (this sort of thing is quite hard to describe concisely and precisely) you may want to see whether the Noda Time &lt;a href="http://noda-time.googlecode.com/hg/docs/userguide/concepts.html"&gt;user guide &amp;quot;concepts&amp;quot; page&lt;/a&gt; helps.&lt;/p&gt;  &lt;h3&gt;The API task: mapping from { LocalDateTime, DateTimeZone } to ZonedDateTime&lt;/h3&gt;  &lt;p&gt;It&amp;#39;s easy to get from a ZonedDateTime to a LocalDateTime - you can just use the LocalDateTime property. The difficult bit is the other way round. We obviously want to be able to create a ZonedDateTime from the combination of a LocalDateTime and a DateTimeZone, but the question is where to put this functionality. Three options suggest themselves:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;A static method (or constructor) in ZonedDateTime which takes both the time zone and the local date/time as arguments &lt;/li&gt;    &lt;li&gt;An instance method on LocalDateTime which just takes the time zone as an argument &lt;/li&gt;    &lt;li&gt;An instance method on DateTimeZone which just takes the local date/time as an argument &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;It gets more complicated though - we&amp;#39;re not really talking about &lt;em&gt;one&lt;/em&gt; operation here, but potentially several. Although the mapping from instant to offset is unambiguous in DateTimeZone, the mapping from LocalDateTime to offset is &lt;em&gt;not &lt;/em&gt;straightforward. There can be 0, 1 or 2 possible results. For example, in the America/Los_Angeles time zone the clocks go forward from 2am to 3am on Sunday March 11th 2012, and go back from 2am to 1am on Sunday 4th November 2012. That means:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The mapping from local date/time to offset at 7.30pm on February 27th 2012 is unambiguous: it&amp;#39;s definitely -8 hours (L.A. is 8 hours &lt;em&gt;behind&lt;/em&gt; UTC). &lt;/li&gt;    &lt;li&gt;The mapping at 2.30am on March 11th 2012 is &lt;em&gt;impossible&lt;/em&gt;: at 2am the clocks were put forward to 3am, so 2.30am simply never occurs. &lt;/li&gt;    &lt;li&gt;The mapping at 2.30am on November 4th 2012 is &lt;em&gt;ambiguous&lt;/em&gt;: it happens once &lt;em&gt;before&lt;/em&gt; the clocks go back at 3am, and once &lt;em&gt;afterwards&lt;/em&gt;. The offset is either -7 or -8 hours, depending on which occurrence you mean. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;When mapping a local time to &amp;quot;global&amp;quot; time, this is something you should really think about. Most APIs obscure the issue, but one of the purposes of Noda Time is to &lt;em&gt;force&lt;/em&gt; developers to think about issues which they should be aware of. This one is particularly insidious in that it&amp;#39;s the kind of problem which is &lt;em&gt;much&lt;/em&gt; more likely to arise when you&amp;#39;re asleep than during daylight hours - so it&amp;#39;s unlikely to be found during manual testing. (Ditto the day of week - most time zones have daylight saving transitions early on a Sunday morning.)&lt;/p&gt;  &lt;p&gt;So, Noda Time exposes four ways of mapping a LocalDateTime and DateTimeZone to a ZonedDateTime:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Exact: if there&amp;#39;s a single mapping, return it. Otherwise, throw an exception. &lt;/li&gt;    &lt;li&gt;Earlier: if there&amp;#39;s a single mapping, return it. If there&amp;#39;s more than one, return the earlier one. If the time is skipped, throw an exception. &lt;/li&gt;    &lt;li&gt;Later: if there&amp;#39;s a single mapping, return it. If there&amp;#39;s more than one, return the later one. If the time is skipped, throw an exception. &lt;/li&gt;    &lt;li&gt;All information: find out all the information relevant to mapping the given local value - how many matches there are, what they would be, what the time zone information is for each mapping, etc. The caller can then do what they want. &lt;/li&gt; &lt;/ul&gt;  &lt;h1&gt;Options available&lt;/h1&gt;  &lt;p&gt;The question is &lt;em&gt;how&lt;/em&gt; we expose these operations. Let&amp;#39;s look at some options, then discuss the pros and cons.&lt;/p&gt;  &lt;h3&gt;Option 1: methods on LocalDateTime&lt;/h3&gt;  &lt;p&gt;A lot of Noda Time is designed to be &amp;quot;fluent&amp;quot; so it makes a certain amount of sense to be able to take a LocalDateTime, perform some arithmetic on it, then convert it to a ZonedDateTime, then (say) format it. So we could have something like:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;var zoned = local.InZone(zone); // implicitly exact &lt;/li&gt;    &lt;li&gt;var zoned = local.InZoneOrEarlier(zone); &lt;/li&gt;    &lt;li&gt;var zoned = local.InZoneOrLater(zone); &lt;/li&gt;    &lt;li&gt;var mapping = local.MapToZone(zone); &lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;Option 2: methods on DateTimeZone&lt;/h3&gt;  &lt;p&gt;All the calculations involved are really about the time zone - the local date/time value is just a simple value as far as most of this is concerned. So we can put the methods on DateTimeZone instead:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;var zoned = zone.AtExactly(local); &lt;/li&gt;    &lt;li&gt;var zoned = zone.AtEarlier(local); &lt;/li&gt;    &lt;li&gt;var zoned = zone.AtLater(local); &lt;/li&gt;    &lt;li&gt;var mapping = zone.MapLocalDateTime(local); &lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;Option 3: methods (or constructors) on ZonedDateTime&lt;/h3&gt;  &lt;p&gt;Maybe we consider the two inputs to be fairly equal, but the result type is more important:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;var zoned = ZonedDateTime.FromLocal(zone, local); &lt;/li&gt;    &lt;li&gt;var zoned = ZonedDateTime.FromLocalOrEarlier(zone, local); &lt;/li&gt;    &lt;li&gt;var zoned = ZonedDateTime.FromLocalOrLater(zone, local); &lt;/li&gt;    &lt;li&gt;var mapping = ZoneLocalMapping.FromLocal(local) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;(I&amp;#39;m not terribly happy about the names here; there could be better ones of course.)&lt;/p&gt;  &lt;h3&gt;Variation a: any of the above options, but with an enum for ambiguity resolution&lt;/h3&gt;  &lt;p&gt;We don&amp;#39;t really need four methods on any of these APIs; the first three only differ by how they handle ambiguity (the situation where a particular local date/time occurs twice). We could use an enum to represent that choice instead:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;var zoned = local.InZone(zone, ZoneAmbiguityResolver.Error); &lt;/li&gt;    &lt;li&gt;var zoned = local.InZone(zone, ZoneAmbiguityResolver.Earlier); &lt;/li&gt;    &lt;li&gt;var zoned = local.InZone(zone, ZoneAmbiguityResolver.Later); &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;(Or a &amp;quot;smart enum&amp;quot; with behaviour, if we wanted. A normal class type with methods etc, but only a restricted set of valid values.)&lt;/p&gt;  &lt;h3&gt;Variation b: always go via the mapping result&lt;/h3&gt;  &lt;p&gt;Given that we already have the idea of getting the full mapping results, we can reduce the API to just &lt;em&gt;one&lt;/em&gt; method to return the mapping information, and then put extra methods on that:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;var zoned = local.MapInZone(zone).SingleMatch; &lt;/li&gt;    &lt;li&gt;var zoned = local.MapInZone(zone).SingleOrEarlier; &lt;/li&gt;    &lt;li&gt;var zoned = local.MapInZone(zone).SingleOrLater; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;(Again, the names aren&amp;#39;t fixed in stone, and the second part could be methods instead of properties if we wanted.)&lt;/p&gt;  &lt;h3&gt;Variation c: return a sequence of results&lt;/h3&gt;  &lt;p&gt;If we return a sequence with 0, 1 or 2 ZonedDateTime values, the user can just use LINQ to get the one they want. Again, this can apply wherever we decide to put the method:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;var zoned = zone.At(local).Single(); &lt;/li&gt;    &lt;li&gt;var zoned = zone.At(local).First(); &lt;/li&gt;    &lt;li&gt;var zoned = zone.At(local).Last(); &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So, it looks like we effectively have two mostly-orthogonal decisions here:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Where to &amp;quot;start&amp;quot; the conversion - the target type for the method call &lt;/li&gt;    &lt;li&gt;How to represent the multiple options &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;We&amp;#39;ll consider them separately.&lt;/p&gt;  &lt;h1&gt;Regarding the &amp;quot;source&amp;quot; type&lt;/h1&gt;  &lt;p&gt;To start with, I&amp;#39;ll reveal my bias: the existing implementation is option 2 (four methods on DateTimeZone). This was after a small amount of debate on the Noda Time mailing list, and this was the most relevant bit of the discussion:&lt;/p&gt;  &lt;p&gt;Me (&lt;em&gt;before&lt;/em&gt; going with the current implementation):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;It feels a little odd to me to use the zone as the principal class here - just in terms of usability. It makes total sense in terms of the logic, but I tend to think of having a LocalDateTime first, and then converting &lt;em&gt;that&lt;/em&gt; to use a particular zone - it&amp;#39;s not an operation which feels like it acts on the zone itself.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;David N:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;I actually feel the opposite: asking a DateTimeZone how a particular LocalDateTime would be represented in that zone feels natural, while asking the LocalDateTime how it would be represented in a zone feels odd. The zone is a first-class entity, with identity and behavior; the LocalDateTime is just a set of values. Why would the LocalDateTime be expected to know how it is represented in a particular zone?&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Even though I replied to that in a &amp;quot;maybe&amp;quot; kind of tone, the argument basically convinced me. The trouble is, a colleague was then &lt;em&gt;surprised&lt;/em&gt; when he read the documentation around calendar arithmetic and conversions. Surprising users is pretty much a cardinal sin when it comes to API design - and although in this case it was the relatively harmless sort of surprise (&amp;quot;I can&amp;#39;t find the member I want in A; oh, it turns out it&amp;#39;s in B&amp;quot;) rather than a &lt;em&gt;behavioural&lt;/em&gt; surprise (&amp;quot;I thought it would do X, but instead it does Y&amp;quot;) it&amp;#39;s still bad news. I should reveal my colleague&amp;#39;s bias too - he has experience of &lt;a href="http://joda-time.sourceforge.net/"&gt;Joda Time&lt;/a&gt;, where the relevant call is &lt;a href="http://joda-time.sourceforge.net/api-release/org/joda/time/LocalDateTime.html#toDateTime(org.joda.time.DateTimeZone)"&gt;LocalDateTime.toDateTime(DateTimeZone)&lt;/a&gt;. (There &lt;em&gt;are&lt;/em&gt; calls in DateTimeZone itself, but they&amp;#39;re lower-level.)&lt;/p&gt;  &lt;p&gt;We&amp;#39;ve discussed this a fair amount (leading to this blog post) and so far we&amp;#39;ve concluded that it really depends on how you &lt;em&gt;think&lt;/em&gt; about time zones. As a Noda Time user, would you consider them to be rich objects with complex behaviour, or would you think of them as mere &amp;quot;tokens&amp;quot; to be passed around and used without much direct interaction? The two ways of viewing the type aren&amp;#39;t necessarily in conflict - I&amp;#39;ve &lt;em&gt;deliberately&lt;/em&gt; designed CalendarSystem to hide its (fairly ugly) innards. There are a few public instance members, but most are internal. But what about time zones?&lt;/p&gt;  &lt;p&gt;There&amp;#39;s an argument to be made for &lt;em&gt;educating&lt;/em&gt; Noda Time users to think about time zones as more complex beasts than just tokens, and I&amp;#39;m happy to do that in other areas (such as choosing which type to use in the first place) but here it feels like it&amp;#39;s one step too far. On the other hand, I don&amp;#39;t want to stifle users who &lt;em&gt;are&lt;/em&gt; thinking of DateTimeZone in that way. In the mailing list thread, David also expressed a dislike for the approach of including functionality in multiple places - and to a certain extent I agree (one of the things I &lt;em&gt;dislike&lt;/em&gt; about its API is that it lets you do just about anything with anything)... but in this case it feels like it&amp;#39;s justified.&lt;/p&gt;  &lt;p&gt;Regardless of how you&amp;#39;re thinking about DateTimeZone, it&amp;#39;s more likely that you&amp;#39;re going to want to &lt;em&gt;use&lt;/em&gt; a LocalDateTime value which is the result of some other expression, and then apply some &amp;quot;constant&amp;quot; zone to it, then potentially keep going. If you think about a LINQ-style pipeline of operations, the part that varies in the conversion is much more likely to be the LocalDateTime than the time zone. As such, a method on LocalDateTime allows for a more fluent calling style:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; zoned = parseResult.Value     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .PlusMonths(1)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .InZone(LondonTimeZone); &lt;/div&gt;  &lt;p&gt;versus:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; zoned = LondonTimeZone.AtExactly(parseResult.Value.PlusMonths(1)); &lt;/div&gt;  &lt;p&gt;Or to keep the code order the same as the execution order:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local = parseResult.Value.PlusMonths(1);     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; zoned = LondonTimeZone.AtExactly(local); &lt;/div&gt;  &lt;p&gt;Obviously the effects become more noticeable the more operations you perform. Personally I&amp;#39;m happy with either the first or third approach - although it&amp;#39;s worth being aware that either of the first &lt;em&gt;two&lt;/em&gt; have the advantage of being one expression, and therefore easy to use when assigning a static readonly field or something similar.&lt;/p&gt;  &lt;p&gt;I&amp;#39;m &lt;em&gt;reasonably&lt;/em&gt; happy with having one method on each type, or possibly two (MapLocalDateTime and At*) on DateTimeZone and one (just InZone) on LocalDateTime. I &lt;em&gt;really&lt;/em&gt; don&amp;#39;t like the idea of having four methods on DateTimeZone and three methods on LocalDateTime. So, let&amp;#39;s consider the different variations which cut down the number of methods required.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Expressing &amp;quot;exactly,&amp;quot; &amp;quot;earlier,&amp;quot; and &amp;quot;later&amp;quot; in one method&lt;/h1&gt;  &lt;p&gt;This is essentially a discussion of the &amp;quot;variations&amp;quot; above. Just to recap, the possibilities we&amp;#39;ve come up with are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Add another parameter to the method to indicate how to handle ambiguities (or impossibilities) - just return a ZonedDateTime &lt;/li&gt;    &lt;li&gt;Return a value of a different type (e.g. ZoneLocalMapping) which can be used to get at all the information you could want &lt;/li&gt;    &lt;li&gt;Return a sequence of possible ZonedDateTime values, expecting the caller to probably use LINQ&amp;#39;s First/Last/Single/FirstOrDefault etc to get at the value they want &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The last of these is the only one which gives an easy way of handling the extreme corner case of a local time occurring &lt;em&gt;more&lt;/em&gt; than twice - for example, a time zone which goes back one hour at 2am (to 1am) and then goes back another two hours at 3am. I think it&amp;#39;s reasonable to dismiss this corner case; however mad time zones can be, I haven&amp;#39;t seen anything &lt;em&gt;quite&lt;/em&gt; that crazy yet.&lt;/p&gt;  &lt;p&gt;At the time of the original discussion, Noda Time was targeting .NET 2.0, which was one reason for not going with the final option here - we couldn&amp;#39;t guarantee that LINQ would be available. Now, Noda Time is targeting .NET 3.5 in order to use TimeZoneInfo, but it still doesn&amp;#39;t feel like an ideal fit:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Returning a sequence doesn&amp;#39;t give information about (say) the two zone intervals &amp;quot;surrounding&amp;quot; a gap &lt;/li&gt;    &lt;li&gt;A sequence may be surprising to users who expect just a single value &lt;/li&gt;    &lt;li&gt;The exceptions thrown by First, Single etc when their expectations aren&amp;#39;t met are very domain-neutral; we can give more information &lt;/li&gt;    &lt;li&gt;FirstOrDefault will return the default value for ZonedDateTime in the case of ambiguity. That would be unfortunate, as ZonedDateTime is a value type, and its default value is actually somewhat unhelpful. (It has a null calendar system, effectively. There&amp;#39;s not a lot we can do about this, but that&amp;#39;s a post for another day.) We could make it a sequence of Nullable&amp;lt;ZonedDateTime&amp;gt; and guarantee that any values in it are actually non-null, but that&amp;#39;s really straining things. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Putting these together, there are enough negative points to this idea that I&amp;#39;m happy to rule it out. But what about the first two?&lt;/p&gt;  &lt;p&gt;The first has the advantage that the caller only needs to make a single method call, effectively passing in a &amp;quot;magic token&amp;quot; (the ambiguity resolver) which they don&amp;#39;t &lt;em&gt;really&lt;/em&gt; need to understand. On the other hand, if they want more information, they&amp;#39;ll have to call a different method - and I&amp;#39;m not really sure we want to encourage too much of this &amp;quot;magic token&amp;quot; behaviour.&lt;/p&gt;  &lt;p&gt;The second has three disadvantages, all fairly slight:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The user may initially expect the result of a method mapping a LocalDateTime to a ZonedDateTime to &lt;em&gt;be&lt;/em&gt; a ZonedDateTime... what&amp;#39;s this extra intermediate result doing? This is &amp;quot;only&amp;quot; a matter of user education, and it&amp;#39;s pretty discoverable. It&amp;#39;s an extra concept the user needs to understand, but it&amp;#39;s a &lt;em&gt;good&lt;/em&gt; concept to understand. &lt;/li&gt;    &lt;li&gt;Calling two methods or a method and a property (e.g. zone.MapLocalDateTime(localDateTime).Earlier) may end up being slightly more long-winded than a single method call. I can&amp;#39;t get excited about this. &lt;/li&gt;    &lt;li&gt;We have to allocate an extra object for the mapping, even when we know it&amp;#39;s unique. Usually, this object will become eligible for garbage collection immediately. We &lt;em&gt;could&lt;/em&gt; make it a struct, but I don&amp;#39;t think it&amp;#39;s a natural value type - I&amp;#39;d rather trust that allocating objects in gen0 is pretty cheap. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;With the second method, we can replace &lt;em&gt;all&lt;/em&gt; the existing methods in DateTimeZone with a single one (or rather, just remove the AtXyz methods, leaving MapLocalDateTime). We can then create pleasantly-named methods on ZoneLocalMapping (which isn&amp;#39;t quite right for this purpose at the moment).&lt;/p&gt;  &lt;h1&gt;Conclusion&lt;/h1&gt;  &lt;p&gt;This has been an interesting thought experiment for me, and it&amp;#39;s suggested some changes I &lt;em&gt;will&lt;/em&gt; be applying before v1. We&amp;#39;ll see how they pan out. If you want to follow them, look for relevant &lt;a href="http://code.google.com/p/noda-time/source/list"&gt;source code changes&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;The important points I&amp;#39;ve been thinking about are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;What would a new user &lt;em&gt;expect&lt;/em&gt; to be available? If they haven&amp;#39;t read any documentation, what are they likely to try? &lt;/li&gt;    &lt;li&gt;What &lt;em&gt;should&lt;/em&gt; the user know about? Where there are important decisions to make, how can we provide guidance? &lt;/li&gt;    &lt;li&gt;What would an &lt;em&gt;experienced&lt;/em&gt; user (who is already thinking about the Noda Time concepts in the way that we want to encourage) expect to be available? &lt;/li&gt;    &lt;li&gt;Where does the balance lie between providing a &amp;quot;too crowded&amp;quot; API (with lots of different ways of achieving the same thing) and a &amp;quot;sparse&amp;quot; API (where there&amp;#39;s always one way of achieving a goal, but it may not be the most convenient one for your situation) &lt;/li&gt;    &lt;li&gt;How does our choice fit in with other technologies? For example, the final &amp;quot;variation&amp;quot; seems like it plays nicely with LINQ at first - but a few subtleties make it a worse fit than it might seem. &lt;/li&gt;    &lt;li&gt;How does this affect performance? (Performance is important in Noda Time - but there would have to be a &lt;em&gt;significant&lt;/em&gt; performance problem for me to deviate from an elegant solution.) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So, any other thoughts? Did we miss some options? What other factors should we have taken into consideration?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1806600" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/mW6QsW6GpVc" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Noda+Time/default.aspx">Noda Time</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Design/default.aspx">Design</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/02/29/subtleties-in-api-design-member-placement.aspx</feedburner:origLink></item><item><title>Currying vs partial function application</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/jeibq6H-CdU/currying-vs-partial-function-application.aspx</link><pubDate>Mon, 30 Jan 2012 18:32:06 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1805414</guid><dc:creator>skeet</dc:creator><slash:comments>35</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1805414</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1805414</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/01/30/currying-vs-partial-function-application.aspx#comments</comments><description>&lt;p&gt;This is a slightly odd post, and before you read it you should probably put yourself into one of three buckets:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Someone who doesn&amp;#39;t care too much about functional programming, and finds higher order functions tricky: feel free to skip this post entirely. &lt;/li&gt;    &lt;li&gt;Someone who knows all about functional programming, and already knows the difference between currying and partial function application: please read this post carefully and post comments about any inaccuracies you find. (Yes, the CAPTCHA is broken on Chrome; sorry.) &lt;/li&gt;    &lt;li&gt;Someone who &lt;em&gt;doesn&amp;#39;t&lt;/em&gt; know much about functional programming yet, but is interested to learn more: please take this post with a pinch of salt, and read the comments carefully. Read other articles by more experienced developers for more information. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Basically, I&amp;#39;ve been aware for a while that some people use the terms &lt;em&gt;currying&lt;/em&gt; and &lt;em&gt;partial function application&lt;/em&gt; somewhat interchangably, when they shouldn&amp;#39;t. It&amp;#39;s one of those topics (like monads) which I feel I understand to some extent, and I&amp;#39;ve decided that the best way of making sure I understand it is to try to write about it. If it helps the topic become more accessible to other developers, so much the better.&lt;/p&gt;  &lt;h3&gt;This post contains no Haskell&lt;/h3&gt;  &lt;p&gt;Almost every explanation I&amp;#39;ve ever seen of either topic has given examples in a &amp;quot;proper&amp;quot; functional language, typically Haskell. I have absolutely nothing against Haskell, but I typically find it easier to understand examples in a programming language I understand. I also find it &lt;em&gt;much&lt;/em&gt; easier to &lt;em&gt;write&lt;/em&gt; examples in a program language I understand, so all the examples in this post are going to be in C#. In fact, it&amp;#39;s all available in a &lt;a href="http://pobox.com/~skeet/csharp/blogfiles/Curry.cs"&gt;single file&lt;/a&gt; - that includes all of the examples, admittedly with a few variables renamed. Just compile and run.&lt;/p&gt;  &lt;p&gt;C# isn&amp;#39;t really a functional language - I know just about enough to understand that delegates aren&amp;#39;t really a proper substitute for first class functions. However, they&amp;#39;re good enough to demonstrate the principles involved.&lt;/p&gt;  &lt;p&gt;While it&amp;#39;s possible to demonstrate currying and partial function application using a function (method) taking a very small number of parameters, I&amp;#39;ve chosen to use 3 for clarity. Although my methods to perform the currying and partial function application will be generic (so all the types of parameters and return value are arbitrary) I&amp;#39;m using a simple function for demonstration purposes:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; SampleFunction(&lt;span class="ValueType"&gt;int&lt;/span&gt; a, &lt;span class="ValueType"&gt;int&lt;/span&gt; b, &lt;span class="ValueType"&gt;int&lt;/span&gt; c)&amp;#160; &lt;br /&gt;{&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;.Format(&lt;span class="String"&gt;&amp;quot;a={0}; b={1}; c={2}&amp;quot;&lt;/span&gt;, a, b, c);&amp;#160; &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;So far, so simple. There&amp;#39;s &lt;em&gt;nothing tricky&lt;/em&gt; about that method, so don&amp;#39;t look for anything surprising.&lt;/p&gt;  &lt;h3&gt;What&amp;#39;s it all about?&lt;/h3&gt;  &lt;p&gt;Both currying and partial function application are about converting one sort of function to another. We&amp;#39;ll use delegates as an approximation to functions, so if we want to treat the method SampleFunction as a value, we can write:&lt;/p&gt;  &lt;div class="code"&gt;Func&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; function = SampleFunction; &lt;/div&gt;  &lt;p&gt;This single line is useful for two reasons:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Assigning the value to a variable hammers home the point that it really is a value. A delegate instance is an object much like any other, and the value of the function variable is a reference just like any other. &lt;/li&gt;    &lt;li&gt;Method group conversions (using just the name of the method as a way of creating a delegate) doesn&amp;#39;t work terribly nicely with type inference when calling a generic method. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;We can already call the function using three arguments with no further work:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; result = function(1, 2, 3); &lt;/div&gt;  &lt;p&gt;Or equivalently:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; result = function.Invoke(1, 2, 3); &lt;/div&gt;  &lt;p&gt;(The C# compiler just converts the shorthand of the first form to the second. The IL emitted will be the same.)&lt;/p&gt;  &lt;p&gt;That&amp;#39;s fine if we&amp;#39;ve got all the arguments available at the same time, but what if we haven&amp;#39;t? To give a concrete (if somewhat contrived) example, suppose we have a logging function with three parameters (source, severity, message) and within a single class (which I&amp;#39;ll call BusinessLogic for the moment) we always want to use the same value for the &amp;quot;source&amp;quot; parameter, and we&amp;#39;d like to be able to log easily everywhere in the class specifying just the severity and message. We have a few options:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Create an adapter class which takes the log function (or more generally a logging object) and the &amp;quot;source&amp;quot; value in its constructor, stashes both in instance variables, and exposes a method with two parameters. That method just delegates to the stashed logger, using the source it&amp;#39;s remembered to supply the first argument to the three-parameter method. In BusinessLogic we create an instance of the adapter class, and stash a reference in an instance variable - then just call the two-parameter method everywhere we need to. This is probably overkill if we only need the adapter from BusinessLogic, but it&amp;#39;s reusable... so long as we&amp;#39;re trying to adapt the same logging function. &lt;/li&gt;    &lt;li&gt;Store the original logger in our BusinessLogic class, but create a helper method with two parameters. This can hard-code the value used for the &amp;quot;source&amp;quot; parameter in one place (the helper method). If we need to do this in several places, it gets annoying. &lt;/li&gt;    &lt;li&gt;Use a more general functional programming approach - probably &lt;em&gt;partial function application&lt;/em&gt; in this case. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I&amp;#39;m deliberately ignoring the discrepancy between holding a reference to &amp;quot;the logger&amp;quot; and holding a reference to &amp;quot;the logging function&amp;quot;. Obviously there&amp;#39;s a significant difference if we need to use more than one function from the logging class, but for the purposes of thinking about currying and partial function application, we&amp;#39;ll just think of &amp;quot;a logger&amp;quot; as &amp;quot;a function taking three parameters&amp;quot; (like our sample function).&lt;/p&gt;  &lt;p&gt;Now that I&amp;#39;ve given the slightly-real-world concrete example for a bit of motivation, I&amp;#39;m going to ignore it for the rest of the post, and just talk about our sample function. I don&amp;#39;t want to write a whole BusinessLogic class which pretends to do something useful; I&amp;#39;m sure you can perform the appropriate mental conversion from &amp;quot;the sample function&amp;quot; to &amp;quot;something I might actually want to do&amp;quot;.&lt;/p&gt;  &lt;h3&gt;Partial Function Application&lt;/h3&gt;  &lt;p&gt;The purpose of partial function application is to take a function with N parameters and a value for one of those parameters, and return a function with N-1 parameters, such that calling the result will assemble all the required values appropriately (the 1 argument given to the partial application operation itself, and the N-1 arguments given to the returned function). So in code form, these two calls should be equivalent for our 3-parameter method:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Normal call &lt;/span&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; result1 = function(1, 2, 3);     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Call via partial application &lt;/span&gt;    &lt;br /&gt;Func&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; partialFunction = ApplyPartial(function, 1);&amp;#160; &lt;br /&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; result2 = partialFunction(2, 3); &lt;/div&gt;  &lt;p&gt;In this case I&amp;#39;ve implemented partial application with a single parameter, and chosen the first one - you &lt;em&gt;could&lt;/em&gt; write an ApplyPartial method which took more arguments to apply, or which used them somewhere else in the final function execution. I believe that picking off parameters one at a time, from the start, is the most conventional approach.&lt;/p&gt;  &lt;p&gt;Thanks to anonymous functions (a lambda expression in this case, but an anonymous method wouldn&amp;#39;t be much more verbose), the implementation of ApplyPartial is simple:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;static&lt;/span&gt; Func&amp;lt;T2, T3, TResult&amp;gt; ApplyPartial&amp;lt;T1, T2, T3, TResult&amp;gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; (Func&amp;lt;T1, T2, T3, TResult&amp;gt; function, T1 arg1)&amp;#160; &lt;br /&gt;{&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; (b, c) =&amp;gt; function(arg1, b, c);&amp;#160; &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The generics make the method look more complicated than it really is. Note that the lack of higher order types in C# means that you&amp;#39;d need a method like this for &lt;em&gt;every&lt;/em&gt; delegate you wanted to use - if you wanted a version for a function which started with four parameters, you&amp;#39;d need an ApplyPartial&amp;lt;T1, T2, T3, T4, TResult&amp;gt; method etc. You&amp;#39;d probably also want a parallel set of methods for the Action delegate family.&lt;/p&gt;  &lt;p&gt;The final thing to note is that assuming we had all of these methods, we could perform partial function application again - even potentially down to a parameterless function if we wanted, like this:&lt;/p&gt;  &lt;div class="code"&gt;Func&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; partial1 = ApplyPartial(function, 1);&amp;#160; &lt;br /&gt;Func&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; partial2 = ApplyPartial(partial1, 2);&amp;#160; &lt;br /&gt;Func&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; partial3 = ApplyPartial(partial2, 3);&amp;#160; &lt;br /&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; result = partial3(); &lt;/div&gt;  &lt;p&gt;Again, only the final line would actually invoke the original function.&lt;/p&gt;  &lt;p&gt;Okay, so that&amp;#39;s partial function application. That&amp;#39;s &lt;em&gt;relatively&lt;/em&gt; straightforward. Currying is slightly harder to get your head round, in my view.&lt;/p&gt;  &lt;h3&gt;Currying&lt;/h3&gt;  &lt;p&gt;Whereas partial function application converts a function with N parameters into a function with N-1 parameters by applying one argument, currying effectively decomposes the function into functions taking a single parameter. We don&amp;#39;t pass any arguments into the Curry method itself:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Curry(f) returns a function f1 such that... &lt;/li&gt;    &lt;li&gt;f1(a) returns a function f2 such that... &lt;/li&gt;    &lt;li&gt;f2(b) returns a function f3 such that... &lt;/li&gt;    &lt;li&gt;f3(c) invokes f(a, b, c) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;(Again, note that this is specific to our three-parameter function - but hopefully it&amp;#39;s obvious how it would extend to other signatures.)&lt;/p&gt;  &lt;p&gt;To give our &amp;quot;equivalence&amp;quot; example again, we can write:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Normal call &lt;/span&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; result1 = function(1, 2, 3);     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Call via currying &lt;/span&gt;    &lt;br /&gt;Func&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, Func&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, Func&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt; f1 = Curry(function);&amp;#160; &lt;br /&gt;Func&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, Func&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; f2 = f1(1);&amp;#160; &lt;br /&gt;Func&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; f3 = f2(2);&amp;#160; &lt;br /&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; result2 = f3(3);     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Or to do make all the calls together... &lt;/span&gt;    &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; curried = Curry(function);&amp;#160; &lt;br /&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; result3 = curried(1)(2)(3); &lt;/div&gt;  &lt;p&gt;The difference between the latter examples shows one reason why functional languages often have good type inference and compact representations of function types: that declaration of f1 is pretty fearsome.&lt;/p&gt;  &lt;p&gt;Now that we know what the Curry method is meant to do, it&amp;#39;s actually surprisingly simple to implement. Indeed, all we need to do is translate the bullet points above into lambda expressions. It&amp;#39;s a thing of beauty:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;static&lt;/span&gt; Func&amp;lt;T1, Func&amp;lt;T2, Func&amp;lt;T3, TResult&amp;gt;&amp;gt;&amp;gt; Curry&amp;lt;T1, T2, T3, TResult&amp;gt;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; (Func&amp;lt;T1, T2, T3, TResult&amp;gt; function)&amp;#160; &lt;br /&gt;{&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; a =&amp;gt; b =&amp;gt; c =&amp;gt; function(a, b, c);&amp;#160; &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;If you want to add some brackets to make it clearer for you, feel free - personally I think it just adds clutter. Either way, we get what we want. (It&amp;#39;s worth thinking about how annoying it would be to write that without lambda expressions or anonymous methods. Not &lt;em&gt;hard&lt;/em&gt;, just annoying.)&lt;/p&gt;  &lt;p&gt;So that&amp;#39;s currying. I think. Maybe.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;I can&amp;#39;t say I&amp;#39;ve ever knowingly used currying, whereas I suspect some bits of &lt;a href="http://noda-time.googlecode.com"&gt;Noda Time&lt;/a&gt;&amp;#39;s text parsing effectively use partial functional application. (If anyone really wants me to dig in and check, I&amp;#39;ll do so.)&lt;/p&gt;  &lt;p&gt;I really hope I&amp;#39;ve got the difference between them right here - it &lt;em&gt;feels&lt;/em&gt; right, in that the two are clearly related, but also quite distinct. Now that we&amp;#39;ve reached the end, think about how that difference manifests itself when there are only two parameters, and hopefully you&amp;#39;ll see why I chose to use three :)&lt;/p&gt;  &lt;p&gt;My gut feeling is that currying is a more useful concept in an academic context, whereas partial functional application is more useful in practice. However, that&amp;#39;s the gut feeling of someone who hasn&amp;#39;t really used a functional language in anger. If I ever &lt;em&gt;really&lt;/em&gt; get round to using F#, maybe I&amp;#39;ll do a follow-up post. For now, I&amp;#39;m hoping that my trusty smart readers can provide useful thoughts for others.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1805414" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/jeibq6H-CdU" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/General/default.aspx">General</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/01/30/currying-vs-partial-function-application.aspx</feedburner:origLink></item><item><title>Eduasync part 19: ordering by completion, ahead of time...</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/t0SgYtV4iDA/eduasync-part-19-ordering-by-completion-ahead-of-time.aspx</link><pubDate>Mon, 16 Jan 2012 22:22:43 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1804970</guid><dc:creator>skeet</dc:creator><slash:comments>18</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1804970</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1804970</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time.aspx#comments</comments><description>&lt;p&gt;Today&amp;#39;s post involves the &lt;a href="http://code.google.com/p/eduasync/source/browse/#hg%2Fsrc%2FMagicOrdering"&gt;MagicOrdering project&lt;/a&gt; in source control (project 28).&lt;/p&gt;  &lt;p&gt;When I wrote &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/11/22/eduasync-part-16-example-of-composition-majority-voting.aspx"&gt;part 16 of Eduasync&lt;/a&gt;, showing composition in the form of majority voting, one reader mailed me a &lt;em&gt;really&lt;/em&gt; interesting suggestion. We don&amp;#39;t really need to wait for &lt;em&gt;any&lt;/em&gt; of the tasks to complete on each iteration of the loop - we only need to wait for the &lt;em&gt;next&lt;/em&gt; task to complete. Now that sounds impossible - sure, it&amp;#39;s great if we know the completion order of the tasks, but half the point of asynchrony is that many things can be happening at once, and we don&amp;#39;t know when they&amp;#39;ll complete. However, it&amp;#39;s not as silly as it sounds.&lt;/p&gt;  &lt;p&gt;If you give me a collection of tasks, I&amp;#39;ll give you back another collection of tasks which will return the same results - but I&amp;#39;ll order them so that the first returned task will have the same result as whichever of your original tasks completes first, and the second returned task will have the same result as whichever of your original tasks completes second, and so on. They won&amp;#39;t be the &lt;em&gt;same&lt;/em&gt; tasks as you gave me, reordered - but they&amp;#39;ll be tasks with the same results. I&amp;#39;ll propagate cancellation, exceptions and so on.&lt;/p&gt;  &lt;p&gt;It still sounds impossible... until you realize that I don&amp;#39;t have to associate one of my returned tasks with one of your original tasks &lt;em&gt;until it has completed&lt;/em&gt;. Before anything has completed, all the tasks look the same. The trick is that as soon as I see one of your tasks complete, I can fetch the result and propagate it to the first of the tasks I&amp;#39;ve returned to you, using TaskCompletionSource&amp;lt;T&amp;gt;. When the second of your tasks completes, I propagate the result to the second of the returned tasks, etc. This is all quite easy using &lt;a href="http://msdn.microsoft.com/en-us/library/dd235663.aspx"&gt;Task&amp;lt;T&amp;gt;.ContinueWith&lt;/a&gt; - barring a few caveats I&amp;#39;ll mention later on.&lt;/p&gt;  &lt;p&gt;Once we&amp;#39;ve built a method to do this, we can then &lt;em&gt;really easily&lt;/em&gt; build a method which is the async equivalent of &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.foreach.aspx"&gt;Parallel.ForEach&lt;/a&gt; (and indeed you could write multiple methods for the various overloads). This will execute a specific action on each task in turn, as it completes... it&amp;#39;s &lt;em&gt;like&lt;/em&gt; repeatedly calling &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenany(v=vs.110).aspx"&gt;Task.WhenAny&lt;/a&gt;, but we only actually need to wait for one task at a time, because we know that the first task in our &amp;quot;completion ordered&amp;quot; collection will be the first one to complete (duh).&lt;/p&gt;  &lt;h3&gt;Show me the code!&lt;/h3&gt;  &lt;p&gt;Enough description - let&amp;#39;s look at how we&amp;#39;ll demonstrate both methods, and then how we implement them.&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task PrintDelayedRandomTasksAsync()     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Random rng = &lt;span class="Keyword"&gt;new&lt;/span&gt; Random();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; values = Enumerable.Range(0, 10).Select(_ =&amp;gt; rng.Next(3000)).ToList();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Initial order: {0}&amp;quot;&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;.Join(&lt;span class="String"&gt;&amp;quot; &amp;quot;&lt;/span&gt;, values));     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; tasks = values.Select(DelayAsync);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; ordered = OrderByCompletion(tasks);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;In order of completion:&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;await&lt;/span&gt; ForEach(ordered, Console.WriteLine);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// Returns a task which delays (asynchronously) by the given number of milliseconds,&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// then return that same number back.&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; DelayAsync(&lt;span class="ValueType"&gt;int&lt;/span&gt; delayMillis)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;await&lt;/span&gt; TaskEx.Delay(delayMillis);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; delayMillis;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The idea is that we&amp;#39;re going to create 10 tasks which each just wait for some random period of time, and return the same time period back. We&amp;#39;ll create them in any old order - but obviously they should complete in (at least roughly) the same order as the returned numbers.&lt;/p&gt;  &lt;p&gt;Once we&amp;#39;ve created the collection of tasks, we&amp;#39;ll call OrderByCompletion to create a &lt;em&gt;second&lt;/em&gt; collection of tasks, returning the same results but this time in completion order - so ordered.ElementAt(0) will be the first task to complete, for example.&lt;/p&gt;  &lt;p&gt;Finally, we call ForEach and pass in the ordered task collection, along with Console.WriteLine as the action to take with each value. We await the resulting Task to mimic blocking until the foreach loop has finished. Note that we &lt;em&gt;could&lt;/em&gt; make this a non-async method and just return the task returned by ForEach, given that that&amp;#39;s our only await expression and it&amp;#39;s right at the end of the method. This would be marginally faster, too - there&amp;#39;s no need to build an extra state machine. See &lt;a href="http://msdn.microsoft.com/en-us/magazine/hh456402.aspx"&gt;Stephen Toub&amp;#39;s article about async performance&lt;/a&gt; for more information.&lt;/p&gt;  &lt;h3&gt;ForEach&lt;/h3&gt;  &lt;p&gt;I&amp;#39;d like to get ForEach out of the way first, as it&amp;#39;s so simple: it&amp;#39;s literally just iterating over the tasks, awaiting them and propagating the result to the action. We get the &amp;quot;return a task which will wait until we&amp;#39;ve finished&amp;quot; for free by virtue of making it an async method.&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// Executes the given action on each of the tasks in turn, in the order of&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// the sequence. The action is passed the result of each task.&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt; Task ForEach&amp;lt;T&amp;gt;(IEnumerable&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; tasks, Action&amp;lt;T&amp;gt; action)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; task &lt;span class="Statement"&gt;in&lt;/span&gt; tasks)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; T value = &lt;span class="Modifier"&gt;await&lt;/span&gt; task;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; action(value);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Simple, right? Let&amp;#39;s get onto the meat...&lt;/p&gt;  &lt;h5&gt;OrderByCompletion&lt;/h5&gt;  &lt;p&gt;This is the tricky bit, and I&amp;#39;ve actually split it into two methods to make it slightly easier to comprehend. The PropagateResult method feels like it could be useful in other composition methods, too.&lt;/p&gt;  &lt;p&gt;The basic plan is:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Copy the input tasks to a list: we need to work out how many there are &lt;em&gt;and&lt;/em&gt; iterate over them, so let&amp;#39;s make sure we only iterate once &lt;/li&gt;    &lt;li&gt;Create a collection of TaskCompletionSource&amp;lt;T&amp;gt; references, one for each input task. Note that we&amp;#39;re not associating any particular input task with any particular completion source - we just need the same number of them &lt;/li&gt;    &lt;li&gt;Declare an integer to keep track of &amp;quot;the next available completion source&amp;quot; &lt;/li&gt;    &lt;li&gt;Attach a continuation to each input task which will be increment the counter we&amp;#39;ve just declared, and propagate the just-completed task&amp;#39;s status &lt;/li&gt;    &lt;li&gt;Return a view onto the collection of TaskCompletionSource&amp;lt;T&amp;gt; values, projecting each one to its Task property &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Once you&amp;#39;re happy with the idea, the implementation isn&amp;#39;t too surprising (although it &lt;em&gt;is&lt;/em&gt; quite long):&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// Returns a sequence of tasks which will be observed to complete with the same set&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// of results as the given input tasks, but in the order in which the original tasks complete.&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; IEnumerable&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; OrderByCompletion&amp;lt;T&amp;gt;(IEnumerable&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; inputTasks)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Copy the input so we know it&amp;#39;ll be stable, and we don&amp;#39;t evaluate it twice&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; inputTaskList = inputTasks.ToList();     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Could use Enumerable.Range here, if we wanted...&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; completionSourceList = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;TaskCompletionSource&amp;lt;T&amp;gt;&amp;gt;(inputTaskList.Count);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;for&lt;/span&gt; (&lt;span class="ValueType"&gt;int&lt;/span&gt; i = 0; i &amp;lt; inputTaskList.Count; i++)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; completionSourceList.Add(&lt;span class="Keyword"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;T&amp;gt;());     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// At any one time, this is &amp;quot;the index of the box we&amp;#39;ve just filled&amp;quot;.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// It would be nice to make it nextIndex and start with 0, but Interlocked.Increment&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// returns the incremented value...&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; prevIndex = -1;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// We don&amp;#39;t have to create this outside the loop, but it makes it clearer&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// that the continuation is the same for all tasks.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Action&amp;lt;Task&amp;lt;T&amp;gt;&amp;gt; continuation = completedTask =&amp;gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; index = Interlocked.Increment(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; prevIndex);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; source = completionSourceList[index];     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; PropagateResult(completedTask, source);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; };     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; inputTask &lt;span class="Statement"&gt;in&lt;/span&gt; inputTaskList)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// TODO: Work out whether TaskScheduler.Default is really the right one to use.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; inputTask.ContinueWith(continuation,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CancellationToken.None,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; TaskContinuationOptions.ExecuteSynchronously,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; TaskScheduler.Default);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; completionSourceList.Select(source =&amp;gt; source.Task);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// Propagates the status of the given task (which must be completed) to a task completion source&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// (which should not be).&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; PropagateResult&amp;lt;T&amp;gt;(Task&amp;lt;T&amp;gt; completedTask,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; TaskCompletionSource&amp;lt;T&amp;gt; completionSource)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;switch&lt;/span&gt; (completedTask.Status)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.Canceled:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; completionSource.TrySetCanceled();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;break&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.Faulted:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; completionSource.TrySetException(completedTask.Exception.InnerExceptions);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;break&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;case&lt;/span&gt; TaskStatus.RanToCompletion:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; completionSource.TrySetResult(completedTask.Result);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;break&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;default&lt;/span&gt;:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// TODO: Work out whether this is really appropriate. Could set&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// an exception in the completion source, of course...&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; ArgumentException(&lt;span class="String"&gt;&amp;quot;Task was not completed&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;You&amp;#39;ll notice there are a couple of TODO comments there. The exception in PropagateResult really &lt;em&gt;shouldn&amp;#39;t&lt;/em&gt; happen - the continuation shouldn&amp;#39;t be called when the task hasn&amp;#39;t completed. I still need to think carefully about how tasks should propagate exceptions though.&lt;/p&gt;  &lt;p&gt;The arguments to ContinueWith are more tricky: working through my TimeMachine class and some unit tests with Bill Wagner last week showed just how little I know about how SynchronizationContext, the task awaiters, task schedulers, and TaskContinuationOptions.ExecuteSynchronously all interact. I would &lt;em&gt;definitely&lt;/em&gt; need to look into that more deeply before TimeMachine was really ready for heavy use... which means &lt;em&gt;you&lt;/em&gt; should probably be looking at the TPL in more depth too.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;Sure enough, when you run the code, the results appear in order, as the tasks complete. Here&amp;#39;s one sample of the output:&lt;/p&gt;  &lt;div class="code"&gt;Initial order: 335 468 1842 1991 2512 2603 270 2854 1972 1327   &lt;br /&gt;In order of completion:    &lt;br /&gt;270    &lt;br /&gt;335    &lt;br /&gt;468    &lt;br /&gt;1327    &lt;br /&gt;1842    &lt;br /&gt;1972    &lt;br /&gt;1991    &lt;br /&gt;2512    &lt;br /&gt;2603    &lt;br /&gt;2854 &lt;/div&gt;  &lt;p&gt;TODOs aside, the code in this post is remarkable (which I can say with modesty, as I&amp;#39;ve only refactored it from the code sent to me by another reader and Stephen Toub). It makes me smile every time I &lt;em&gt;think&lt;/em&gt; about the seemingly-impossible job it accomplishes. I suspect this approach could be useful in any number of composition blocks - it&amp;#39;s definitely one to remember.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1804970" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/t0SgYtV4iDA" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time.aspx</feedburner:origLink></item><item><title>Coding in the style of Glee</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/8MoNrulucZg/coding-in-the-style-of-glee.aspx</link><pubDate>Sun, 15 Jan 2012 20:07:55 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1804883</guid><dc:creator>skeet</dc:creator><slash:comments>0</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1804883</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1804883</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/01/15/coding-in-the-style-of-glee.aspx#comments</comments><description>&lt;p&gt;As &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2012/01/15/codemash-2012-report.aspx"&gt;previously mentioned&lt;/a&gt;, at CodeMash 2012 I gave a very silly Pecha Kucha talk entitled &amp;quot;Coding in the style of Glee&amp;quot;. The video is &lt;a href="http://youtu.be/xDTJ6iVgMWs?hd=1"&gt;on YouTube&lt;/a&gt;, or can be seen embedded below:&lt;/p&gt; &lt;iframe height="315" src="http://www.youtube.com/embed/xDTJ6iVgMWs" frameborder="0" width="560"&gt;&lt;/iframe&gt;  &lt;p&gt;(There&amp;#39;s also &lt;a href="http://youtu.be/11u_DwaT3Zw?hd=1"&gt;another YouTube video&lt;/a&gt; from a different angle.)&lt;/p&gt;  &lt;p&gt;This post gives the 20 slides (which were just text; no fancy pictures unlike my competitors) and what I &lt;em&gt;meant&lt;/em&gt; to say about them. (Edited very slightly to remove a couple of CodeMash-specific in-jokes.) Don&amp;#39;t forget that each slide was only up for 20 seconds.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Coding in the style of Glee&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;As you may know, I’m from the UK, and it’s wonderful to be here. This is my first US conference, so it’s great to be in the country which has shared with the world its most marvellous cultural output: the Fox show, Glee.&lt;/p&gt;  &lt;p&gt;At first I watched it just for surface story – but now I know better – I know that really, the songs are all about the culture and practice of coding.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;(It isn&amp;#39;t easy) Bein&amp;#39; Green&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;When I started coding, it was on a ZX Spectrum, in Basic. It was hard, but the computer came with a great manual. I later learned C from a ringbinder of some course or other – and entirely failed to understand half the language. Of course, this was before Stack Overflow, when it was really hard being a newbie – where could you turn for information?&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Getting to know you&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Over time I became semi-competent in C, with the help of friends. But learning is a constant process, of course – getting to know new languages and platforms is just part of a good dev&amp;#39;s life every day.&lt;/p&gt;  &lt;p&gt;Learning itself is a skill – how similar it is to getting to know small children, I leave to your imagination.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Man in the Mirror&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Glee doesn’t just talk about the coding experience, of course – it talks about specific technologies. This Michael Jackson song is talking about reflection, of course. Although the idea wasn’t new in Java, it was new to me – and now it would be almost unthinkable to come up with a new platform which didn’t let you find out about what was in the code.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Bridge over Troubled Water&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Another technology covered beautifully by Glee is the interop. We’re in a big world, and we always need to talk to other systems. Whether it’s over JNI (heaven help you), P/Invoke, SOAP, REST – whatever, I hope next time you connect to another system, you’ll hear this haunting Simon and Garfunkel melody in the background.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;I will survive&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;And who could forget persistence frameworks. I’m not sure whether Gloria Gaynor had Hibernate and the Entity Framework in mind when she sang this, but I’m utterly convinced that the Glee writers did. When you submit your data, it’s just got to survive – what else would you want?&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;You can&amp;#39;t always get what you want&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;We’d all like perfect specifications, reliable libraries, ideal languages, etc – but that’s just not going to happen. It’s possible that of course you won’t get what you need – even if you try real hard. But hey, you might just. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Lean on me (or Agile on me)&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;(I didn&amp;#39;t actually have notes written for this one. Copied from the video.)&lt;/p&gt;  &lt;p&gt;Glee sympathizes with you - but it also have a bit of an answer: lean on me. Lean and agile development, so we can adapt to constantly changing specifications, and eventually we will have something that is useful. Maybe nothing like what we initially envisaged, but it will be something useful.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Losing my Religion&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Of course, we don’t always stay in love with a platform. I’d like to dedicate this slight to Enterprise Java. Fortunately I never had to deal with Enterprise Java Beans, but I “enjoyed” enough other J2EE APIs to make me yearn for a world without BeanProcessorFactoryFactories.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Anything Goes&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Now I’m pretty conservative – only in terms of coding, mind you. I’m a statically typed language guy. But Glee celebrates dynamic languages too – languages where really, anything goes until you try to execute it. Even though I haven’t gone down the dynamic route myself much, it’s important that we all welcome the diversity of languages and platforms we have.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Get Happy&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Along with the rise of dynamic languages, we seem to have seen a rise of happy developers. We’ve always had enthusiastic developers, but there’s a certain air about your typical Ruby on Rails developer which feels new to me. Again, I’m not a Ruby fan myself – but it’s always nice to see other happy people, and maybe one day I’ll see the light.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Bust your Windows&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I don’t know what I can say about this song. Do the Glee writers have it in for Microsoft? I don’t remember “Bust your OSX” or “Bust your Linux” for example. Only Windows is targeted here.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;The Safety Dance&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;One big change for me since joining Google is increased awareness of the need for redundancy – the intricate dance we need to perform to create a service which will stay up no matter what. Where redundancy is a dirty word in most of industry, as developers we celebrate it – and will do anything we can to avoid…&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;The Only Exception&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;… a single point of failure.&lt;/p&gt;  &lt;p&gt;(Yes, that really is all I&amp;#39;d prepared for that slide. Hence the need for improvisation.)&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Telephone&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;(From video.) Glee celebrates the rise of phone apps. Who these days could be unaware of the importance of the development of mobile applications? And obviously, we can credit the iPhone for that, but since the iPhone, and just smart phone apps, we&amp;#39;ve also started...&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;U Can&amp;#39;t Touch This&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;(From video.) Tablets! And touch screen devices of all kinds. So Windows 8 - very touch-based, and sooner or later we&amp;#39;re all going to have to get with it. I don&amp;#39;t do UIs, I&amp;#39;ve never done a touch UI in my life, I have no idea how it works. But clearly it&amp;#39;s one of the ways forward.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Forget You&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;As smart phones and tablets become more ubiquitous and more bound to us as people, privacy has become more important. Glee gave us a timely reminder of the reverse of the persistence early on: we need to be able to forget about users, as well as remember them.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;(A)waiting for a girl like you&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;(From video.) I&amp;#39;d like to leave on an up-note, so: I&amp;#39;m clearly very, very excited (really, really excited) about C# 5 and its await keyword so I ask you - I beg you - be &lt;em&gt;excited&lt;/em&gt; about development. And always bear in mind your users.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;My life would suck without you&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Users rule our world. Can’t live without them, can’t shoot ‘em.&lt;/p&gt;  &lt;p&gt;Celebrate – we do stuff to make users really happy! This is awesome! We should be thrilled!&lt;/p&gt;  &lt;p&gt;(Even for enterprise apps, we’re doing useful stuff. Honest.)&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Don&amp;#39;t stop believing&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;(From video.) So to sum up: have fun, keep learning, really, really enjoy what you&amp;#39;re doing, and... don&amp;#39;t stop!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1804883" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/8MoNrulucZg" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/General/default.aspx">General</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Speaking+engagements/default.aspx">Speaking engagements</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/01/15/coding-in-the-style-of-glee.aspx</feedburner:origLink></item><item><title>CodeMash 2012 report</title><link>http://feedproxy.google.com/~r/JonSkeetCodingBlog/~3/U1lOnDVXmy4/codemash-2012-report.aspx</link><pubDate>Sun, 15 Jan 2012 19:38:42 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1804880</guid><dc:creator>skeet</dc:creator><slash:comments>7</slash:comments><wfw:commentRss>http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1804880</wfw:commentRss><wfw:comment>http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1804880</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/01/15/codemash-2012-report.aspx#comments</comments><description>&lt;p&gt;I&amp;#39;m nearly home - on a bus back from Heathrow airport to Reading - returning from &lt;a href="http://codemash.org/"&gt;CodeMash 2012&lt;/a&gt;. This was my first US conference, and I had a &lt;em&gt;wonderful&lt;/em&gt; time. It was pretty densely packed in terms of presenting / recording for me:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;I presented two back-to-back sessions jointly with Bill Wagner, on async. These went down really well (particularly Bill&amp;#39;s genius idea of using the Doctor Who quote about time being a &amp;quot;big ball of wibbly-wobbly, timey-wimey stuff&amp;quot;) and were &lt;em&gt;great&lt;/em&gt; fun to give. Bill&amp;#39;s a class act, and I think we got the balance between use and underpinnings about right. &lt;/li&gt;    &lt;li&gt;I recorded a &lt;a href="http://hanselminutes.com/"&gt;podcast with Scott Hanselman&lt;/a&gt; (we were going to record two, but the first one ended up being longer than expected) &lt;/li&gt;    &lt;li&gt;I presented a talk on &amp;quot;C#&amp;#39;s Greatest Mistakes&amp;quot; which ended up being somewhere between a discussion on language design, and a demonstration of surprising &amp;quot;features&amp;quot; of C#. It overran by 15 minutes without me coming &lt;em&gt;close&lt;/em&gt; to running out of things to say, but hopefully it was useful. It was a somewhat rambly session, but at least I warned folks of that up-front. It would be nice to be able to present the same sort of material in a really &amp;quot;tight&amp;quot; way, but I&amp;#39;m just not sure how to. &lt;/li&gt;    &lt;li&gt;I gave a 20x20 &amp;quot;Pecha Kucha&amp;quot; talk called &amp;quot;Coding in the style of Glee&amp;quot; as the silliest topic I could come up with on short notice. This was absolutely terrifying and extremely silly. I only came third in the contest (and the winner, Leon, was simply &lt;em&gt;phenomenal&lt;/em&gt;) but I was happy that I&amp;#39;d only embarrassed myself about as much as I&amp;#39;d expected to. The &lt;a href="http://youtu.be/xDTJ6iVgMWs?hd=1"&gt;YouTube video&lt;/a&gt; of this is already up, and I&amp;#39;ll write a blog post with the slide titles and what I was &lt;em&gt;trying&lt;/em&gt; to say in them :)&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Unfortunately due to last minute async prep and desperately trying to cobble together slides for the Glee talk, I didn&amp;#39;t have time to actually attend as many talks as I&amp;#39;d have liked. Even though I was &lt;em&gt;present&lt;/em&gt; for the whole of the Scala Koans session in the PreCompilr on Wednesday, I found myself next to &lt;a href="http://mindviewinc.com/Index.php"&gt;Bruce Eckel&lt;/a&gt;, and ended up chatting with him for most of the time. It would have been a bit of a waste not to, really. (And at least &lt;em&gt;some&lt;/em&gt; of that talking was Scala-related...) I also watched the whole of the &lt;a href="http://www.bradygaster.com/codemash-signalr-talk"&gt;SignalR presentation by Brady Gaster&lt;/a&gt; - where I was apparently the only person in the room with an aversion to &amp;quot;dynamic&amp;quot; in C# 4. That made me the butt of a &lt;em&gt;few&lt;/em&gt; jokes, but not too many for comfort.&lt;/p&gt;  &lt;p&gt;In terms of C#-related talks, I went to the first half of Dustin Campbell&amp;#39;s Roslyn session, but was somewhat distracted by putting together Glee slides and had to leave half way through to hand them in. My final session of the conference was Bill Wagner&amp;#39;s &amp;quot;Stunt coding in C# - I dare you to try this at home&amp;quot; which was excellent, and a very fitting end to the conference for me.&lt;/p&gt;  &lt;p&gt;Highlights of the conference for me:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Messing with Bill Wagner&amp;#39;s code at the end of not just our joint async talk but also his Stunt Coding talk. I&amp;#39;ve never before asked a presented whether they mind me just stealing the keyboard, but I was confident that Bill (and the attendees) would get a kick out of it - and the code &lt;em&gt;was&lt;/em&gt; nicer afterwards :) &lt;/li&gt;    &lt;li&gt;Meeting &lt;em&gt;so&lt;/em&gt; many people... some that I&amp;#39;ve met before (I hadn&amp;#39;t seen &lt;a href="http://www.tedneward.com/"&gt;Ted Neward&lt;/a&gt; since I gate-crashed a party at his house after the MVP 2005 Summit), some I&amp;#39;d met virtually but not physically before (like Bill) and there loads of other folks I&amp;#39;d never known at all before - including &lt;a href="https://twitter.com/#!/coridrew"&gt;Cori Drew&lt;/a&gt;. Cori simply seemed to pop up &lt;em&gt;everywhere -&lt;/em&gt; I swear she had about 20 clones at CodeMash. (She also recorded the video of the Glee talk, and it&amp;#39;s her laughter you can hear - thanks very much, Cori!) Everyone at the conference was incredibly friendly, and I was really touched by how many people said on the last day that they&amp;#39;d appreciated me making the long trip.&lt;/li&gt;    &lt;li&gt;Confounding &lt;a href="https://twitter.com/#!/dcampbell"&gt;Dustin Campbell&lt;/a&gt; and &lt;a href="https://twitter.com/#!/pilchie"&gt;Kevin Pilch-Bisson&lt;/a&gt; with my &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2010/11/02/evil-code-overload-resolution-workaround.aspx"&gt;evil generic overloading puzzle&lt;/a&gt;. Just to be clear, these are two seriously smart guys and this was a friendly over-lunch challenge. It&amp;#39;s always a privilege to meet more of the team responsible for C# and Visual Studio.&lt;/li&gt;    &lt;li&gt;The number of families who came - this is something I&amp;#39;ve never seen at other conferences, and it really made a difference in terms of the atmosphere of the non-dev bits. It was fabulous to see the kids in the water park, for example. Even out of just attendees, there was a greater proportion of women at CodeMash than at other conferences I&amp;#39;ve been to - obviously still vastly outnumbered by the men, but it was nice to see &lt;em&gt;some&lt;/em&gt; improvement on that front. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;This will probably be my only international conference for 2012, so it&amp;#39;s a good job that it was so wonderfully organized. I really hope I have the chance to attend next year too. Many thanks to everyone who helped make it such a special conference.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1804880" width="1" height="1"&gt;&lt;img src="http://feeds.feedburner.com/~r/JonSkeetCodingBlog/~4/U1lOnDVXmy4" height="1" width="1"/&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Speaking+engagements/default.aspx">Speaking engagements</category><feedburner:origLink>http://msmvps.com/blogs/jon_skeet/archive/2012/01/15/codemash-2012-report.aspx</feedburner:origLink></item></channel></rss>
