<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://msmvps.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Jon Skeet: Coding Blog : C#, Stack Overflow</title><link>http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/Stack+Overflow/default.aspx</link><description>Tags: C#, Stack Overflow</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><item><title>Upcoming speaking engagements</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/09/02/upcoming-speaking-engagements.aspx</link><pubDate>Fri, 02 Sep 2011 16:53:17 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1798771</guid><dc:creator>skeet</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1798771</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1798771</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/09/02/upcoming-speaking-engagements.aspx#comments</comments><description>&lt;p&gt;It&amp;#39;s just occurred to me that I&amp;#39;ve forgotten to mention a few of the things I&amp;#39;ll be up to in the near-ish future. (I&amp;#39;ve &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2011/07/28/speaking-engagement-progressive-net-london-september-7th.aspx"&gt;talked about next week&amp;#39;s Progressive .NET session before&lt;/a&gt;.) This is just a quick rundown - follow the links for more blurb and details.&lt;/p&gt;  &lt;h2&gt;.NET Developer Network - Bristol, September 21st (evening)&lt;/h2&gt;  &lt;p&gt;I&amp;#39;ll be &lt;a href="http://dotnetdevnet.com/Meetings/tabid/54/EntryID/58/Default.aspx"&gt;talking about async&lt;/a&gt; in Bristol - possibly at a high level, possibly in detail, depending on the audience experience. This is my first time talking with this particular user group, although I&amp;#39;m sure there&amp;#39;ll be some familiar faces. Come along if you&amp;#39;re in the area.&lt;/p&gt;  &lt;h2&gt;Øredev 2011 - Malmö, November 9th&lt;/h2&gt;  &lt;p&gt;It&amp;#39;s a whistle-stop trip to Sweden as I&amp;#39;m running out of vacation days; I&amp;#39;m flying out on the Tuesday evening and back on the Wednesday evening, but while I&amp;#39;m there I&amp;#39;ll give two talks:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://oredev.org/2011/sessions/async-101"&gt;Async 101&lt;/a&gt; (yes, &lt;em&gt;more&lt;/em&gt; async; I wonder at what point I&amp;#39;ll have given as many talks about it as Mads) &lt;/li&gt;    &lt;li&gt;&lt;a href="http://oredev.org/2011/sessions/a-less-technical-talk-on-technical-communication"&gt;Effective technical communication&lt;/a&gt; (not a particularly technical talk, but definitely specific to &lt;em&gt;technical&lt;/em&gt; communication) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Last year I had an absolute blast - looking forward to this year, even though I won&amp;#39;t have as much time for socializing.&lt;/p&gt;  &lt;h2&gt;Stack Overflow Dev Days 2011 - London, November 14th - cancelled!&lt;/h2&gt;  &lt;p&gt;&lt;strong&gt;Update: &lt;a href="http://blog.stackoverflow.com/2011/09/devdays-2011-is-cancelled/"&gt;Dev Days has been cancelled&lt;/a&gt;. I&amp;#39;m still hoping to do &lt;em&gt;something&lt;/em&gt; around this topic, and there may be small-scale meet-ups in London anyway.&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Two years ago I talked about &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2009/11/02/omg-ponies-aka-humanity-epic-fail.aspx"&gt;how humanity had let the world of software engineering down&lt;/a&gt;. This was one of the best talks I&amp;#39;ve ever given, and introduced the world to Tony the Pony. Unfortunately that puts the bar relatively high for this year&amp;#39;s talk - at least, high by my own pretty low standards.&lt;/p&gt;  &lt;p&gt;In a somewhat odd topic for a &lt;a href="http://pobox.com/~skeet/preaching"&gt;Christian&lt;/a&gt; and a happy employee of a company with a &lt;a href="http://investor.google.com/corporate/code-of-conduct.html"&gt;code of conduct&lt;/a&gt; which starts &amp;quot;Don&amp;#39;t be evil,&amp;quot; this year&amp;#39;s talk is entitled &lt;a href="http://devdays.stackoverflow.com/sessions/thinking-in-evil/"&gt;&amp;quot;Thinking in evil.&amp;quot;&lt;/a&gt; As regular readers are no doubt aware, I love torturing the C# language and forcing the compiler to work with code which would make any right-thinking software engineer cringe. I was particularly gratified recently when Eric Lippert commented on &lt;a href="http://stackoverflow.com/questions/7113347/c-assignment-in-an-if-statement/7113387#7113387"&gt;one of my Stack Overflow answers&lt;/a&gt; that this was &amp;quot;the best abuse of C# I&amp;#39;ve seen in a while.&amp;quot; I&amp;#39;m looking forward to talking about why I think it&amp;#39;s genuinely a good idea to think about nasty code like this - not to &lt;em&gt;use&lt;/em&gt; it, but to get to know your language of choice more intimately. Like last time, I have little idea of &lt;em&gt;exactly&lt;/em&gt; what this talk will be like, but I&amp;#39;m really looking forward to it.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1798771" width="1" height="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/Speaking+engagements/default.aspx">Speaking engagements</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Evil+Code/default.aspx">Evil Code</category></item><item><title>"Magic" null argument testing</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/12/09/quot-magic-quot-null-argument-testing.aspx</link><pubDate>Wed, 09 Dec 2009 18:04:47 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1744445</guid><dc:creator>skeet</dc:creator><slash:comments>51</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1744445</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1744445</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/12/09/quot-magic-quot-null-argument-testing.aspx#comments</comments><description>&lt;p&gt;Warning: here be dragons. I don&amp;#39;t think this is the right way to check for null arguments, but it was an intriguing idea.&lt;/p&gt;  &lt;p&gt;Today on Stack Overflow, I answered a &lt;a href="http://stackoverflow.com/questions/1873264"&gt;question about checking null arguments&lt;/a&gt;. The questioner was already using an extension similar to my own one in &lt;a href="http://pobox.com/~skeet/csharp/miscutil"&gt;MiscUtil&lt;/a&gt;, allowing code like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; DoSomething(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; name)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; name.ThrowIfNull(&lt;span class="String"&gt;&amp;quot;name&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Normal code here&lt;/span&gt;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;That&amp;#39;s all very well, but it&amp;#39;s annoying to have to repeat the &lt;code&gt;name&lt;/code&gt; part. Now in an ideal world, I&amp;#39;d say it would be nice to add an attribute to the parameter and have the check performed automatically (and when PostSharp works with .NET 4.0, I&amp;#39;m going to give that a go, mixing Code Contracts and AOP…) – but for the moment, how far can we go with extension methods?&lt;/p&gt;  &lt;p&gt;I stand by my answer from that question – the code above is the simplest way to achieve the goal for the moment… but another answer raised the interesting prospect of combining anonymous types, extension methods, generics, reflection and manually-created expression trees. Now that&amp;#39;s a recipe for hideous code… but it actually works.&lt;/p&gt;  &lt;p&gt;The idea is to allow code like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; DoSomething(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; name, &lt;span class="ReferenceType"&gt;string&lt;/span&gt; canBeNull, &lt;span class="ValueType"&gt;int&lt;/span&gt; foo, Stream input)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;new&lt;/span&gt; { name, input }.CheckNotNull();     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Normal code here&lt;/span&gt;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;That should check &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;input&lt;/code&gt;, in that order, and throw an appropriate &lt;code&gt;ArgumentNullException&lt;/code&gt; - including parameter name - if one of them is null. It uses the fact that projection initializers in anonymous types use the primary expression&amp;#39;s name as the property name in the generated type, and the value of that expression ends up in the instance. Therefore, given an instance of the anonymous type initializer like the above, we have both the name and value despite having only typed it in once.&lt;/p&gt;  &lt;p&gt;Now obviously this &lt;em&gt;could&lt;/em&gt; be done with normal reflection – but that we be slow as heck. No, we want to effectively find the properties &lt;em&gt;once&lt;/em&gt;, and generate strongly typed delegates to perform the property access. That sounds like a job for &lt;a href="http://msdn.microsoft.com/en-us/library/system.delegate.createdelegate.aspx"&gt;Delegate.CreateDelegate&lt;/a&gt;, but it&amp;#39;s not quite that simple… to create the delegate, we&amp;#39;d need to know (at compile time) what the property type is. We could do that with another generic type, but we can do better than that. All we really need to know about the value is whether or not it&amp;#39;s null. So given a &amp;quot;container&amp;quot; type &lt;code&gt;T&lt;/code&gt;, we&amp;#39;d like a bunch of delegates, one for each property, returning whether that property is null for a specified instance – i.e. a &lt;code&gt;Func&amp;lt;T, bool&amp;gt;&lt;/code&gt;. And how do we build delegates at execution time with custom logic? We use expression trees…&lt;/p&gt;  &lt;p&gt;I&amp;#39;ve now implemented this, along with a brief set of unit tests. The irony is that the tests took longer than the implementation (which isn&amp;#39;t very unusual) – and so did writing it up in this blog post. I&amp;#39;m not saying that it couldn&amp;#39;t be improved (and indeed in .NET 4.0 I could probably make the delegate throw the relevant exception itself) but it works! I haven&amp;#39;t benchmarked it, but I&amp;#39;d expect it to be nearly as fast as manual tests – insignificant in methods that do real work. (The same wouldn&amp;#39;t be true using reflection every time, of course.)&lt;/p&gt;  &lt;p&gt;The full project including test cases is &lt;a href="http://pobox.com/~skeet/csharp/blogfiles/NullMagic.zip"&gt;now available&lt;/a&gt;, but here&amp;#39;s the (almost completely uncommented) &amp;quot;production&amp;quot; code.&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.Generic;    &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Linq;    &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Reflection;    &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Linq.Expressions;    &lt;br /&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="ReferenceType"&gt;class&lt;/span&gt; Extensions    &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="ValueType"&gt;void&lt;/span&gt; CheckNotNull&amp;lt;T&amp;gt;(&lt;span class="Keyword"&gt;this&lt;/span&gt; T container) &lt;span class="Linq"&gt;where&lt;/span&gt; T : &lt;span class="ReferenceType"&gt;class&lt;/span&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="Statement"&gt;if&lt;/span&gt; (container == &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;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="String"&gt;&amp;quot;container&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; NullChecker&amp;lt;T&amp;gt;.Check(container);    &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="ReferenceType"&gt;class&lt;/span&gt; NullChecker&amp;lt;T&amp;gt; &lt;span class="Linq"&gt;where&lt;/span&gt; T : &lt;span class="ReferenceType"&gt;class&lt;/span&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="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; List&amp;lt;Func&amp;lt;T, &lt;span class="ValueType"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt; checkers;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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; List&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; names;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt; NullChecker()    &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; checkers = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;Func&amp;lt;T, &lt;span class="ValueType"&gt;bool&lt;/span&gt;&amp;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; names = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&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; &lt;span class="InlineComment"&gt;// We can&amp;#39;t rely on the order of the properties, but we&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;// can rely on the order of the constructor parameters&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;// in an anonymous type - and that there&amp;#39;ll only be&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;// one constructor.&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;foreach&lt;/span&gt; (&lt;span class="ReferenceType"&gt;string&lt;/span&gt; name &lt;span class="Statement"&gt;in&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(T).GetConstructors()[0]    &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;&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; .GetParameters()    &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;&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; .Select(p =&amp;gt; p.Name))    &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; names.Add(name);    &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; PropertyInfo property = &lt;span class="Keyword"&gt;typeof&lt;/span&gt;(T).GetProperty(name);    &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="InlineComment"&gt;// I&amp;#39;ve omitted a lot of error checking, but here&amp;#39;s&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;span class="InlineComment"&gt;// at least one bit...&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;span class="Statement"&gt;if&lt;/span&gt; (property.PropertyType.IsValueType)    &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; &lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; ArgumentException    &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; (&lt;span class="String"&gt;&amp;quot;Property &amp;quot;&lt;/span&gt; + property + &lt;span class="String"&gt;&amp;quot; is a value type&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;&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; ParameterExpression param = Expression.Parameter(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(T), &lt;span class="String"&gt;&amp;quot;container&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;&amp;#160;&amp;#160;&amp;#160; Expression propertyAccess = Expression.Property(param, property);    &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; Expression nullValue = Expression.Constant(&lt;span class="Keyword"&gt;null&lt;/span&gt;, property.PropertyType);    &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; Expression equality = Expression.Equal(propertyAccess, nullValue);    &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="Linq"&gt;var&lt;/span&gt; lambda = Expression.Lambda&amp;lt;Func&amp;lt;T, &lt;span class="ValueType"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt;(equality, param);    &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; checkers.Add(lambda.Compile());    &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;    &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;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Check(T item)    &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;for&lt;/span&gt; (&lt;span class="ValueType"&gt;int&lt;/span&gt; i = 0; i &amp;lt; checkers.Count; i++)    &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; (checkers[i](item))    &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; &lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; ArgumentNullException(names[i]);    &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; }    &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;Oh, and just as a miracle – the expression tree worked first time. I&amp;#39;m no Marc Gravell, but I&amp;#39;m clearly improving :)&lt;/p&gt;  &lt;p&gt;&lt;b&gt;Update:&lt;/b&gt; Marc Gravell pointed out that the order of the results of &lt;code&gt;Type.GetProperties&lt;/code&gt; isn&amp;#39;t guaranteed - something I should have remembered myself. However, the order of the constructor parameters &lt;i&gt;will&lt;/i&gt; be the same as in the anonymous type initialization expression, so I&amp;#39;ve updated the code above to reflect that. Marc also showed how it could almost all be put into a single expression tree which returns either null (for no error) or the name of the &amp;quot;failing&amp;quot; parameter. Very clever :) &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1744445" width="1" height="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/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Evil+Code/default.aspx">Evil Code</category></item><item><title>Just how spiky is your traffic?</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/11/16/just-how-spiky-is-your-traffic.aspx</link><pubDate>Mon, 16 Nov 2009 19:48:19 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1740046</guid><dc:creator>skeet</dc:creator><slash:comments>14</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1740046</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1740046</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/11/16/just-how-spiky-is-your-traffic.aspx#comments</comments><description>&lt;p&gt;No, this isn&amp;#39;t the post about dynamic languages I promise. That will come soon. This is just a quick interlude. This afternoon, while answering a question on Stack Overflow&lt;sup&gt;1&lt;/sup&gt; about the difference between using an array and a Dictionary&amp;lt;string, string&amp;gt; (where each string was actually the string representation of an integer) I posted the usual spiel about preferring readable code to micro-optimisation. The response in a comment - about the performance aspect - was:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Well that&amp;#39;s not so easily said for a .com where performance on a site that receives about 1 million hits a month relies on every little ounce of efficiency gains you can give it.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;A million hits a month, eh? That sounds quite impressive, until you actually break it down. Let&amp;#39;s take a month of 30 days - that has 30 * 24 * 60 * 60 = 2,592,000 seconds&lt;sup&gt;2&lt;/sup&gt;. In other words, a million hits a month is less than one hit every two seconds. Not so impressive. At Google we tend to measure traffic in QPS (queries per second, even if they&amp;#39;re not really queries - the search terminology becomes pervasive) so this is around 0.39 QPS. Astonished that someone would make such a claim in favour of micro-optimisation at that traffic level, I &lt;a href="http://twitter.com/jonskeet/status/5767353745"&gt;tweeted about it&lt;/a&gt;. Several of the replies were along the lines of &amp;quot;yeah, but traffic&amp;#39;s not evenly distributed.&amp;quot; That&amp;#39;s entirely true. Let&amp;#39;s see how high we can make the traffic without going absurd though.&lt;/p&gt;  &lt;p&gt;Let&amp;#39;s suppose this is a site which is only relevant on weekdays - that cuts us down to 20 days in the month. Now let&amp;#39;s suppose it&amp;#39;s only relevant for one hour per day - it&amp;#39;s something people look at when they get to work, and most of the users are in one time zone. That&amp;#39;s a pretty massive way of spiking. We&amp;#39;ve gone down from 30 full days of traffic to 20 hours - or 20 * 60 * 60 = 72000 seconds, giving 14 QPS. Heck, let&amp;#39;s say the peak of the spike is double that - a whopping 28 QPS.&lt;/p&gt;  &lt;p&gt;Three points about this:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;28 QPS is still not a huge amount of traffic.&lt;/li&gt;    &lt;li&gt;If you&amp;#39;re &lt;em&gt;really&lt;/em&gt; interested in handling peak traffic of ~28 QPS without latency becoming huge, it&amp;#39;s worth quoting &lt;em&gt;that&lt;/em&gt; figure rather than &amp;quot;a million hits a month&amp;quot; because the latter is somewhat irrelevant, and causes us to make wild (and probably wildly inaccurate) guesses about your load distribution.&lt;/li&gt;    &lt;li&gt;If you&amp;#39;re going to bring the phrase &amp;quot;a .com&amp;quot; into the picture, attempting to make it sound particularly important, you really shouldn&amp;#39;t be thinking about hosting your web site on one server - so the QPS gets diluted again.&lt;/li&gt;    &lt;li&gt;Even at 28 QPS, the sort of difference that would be made here is tiny. A quick microbenchmark (with all the associated caveats) showed that on my laptop (hardly a server-class machine) I could build the dictionary and index into it 3 times 2.8 &lt;em&gt;million&lt;/em&gt; times in about 5 seconds. If every request needed to do that 100 times, then the cost of doing it 28 requests per second on my laptop would still only be 0.5% of that second - not a really significant benefit, despite the hugely exaggerated estimates of how often we needed to do that.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;There are various other ways in which it&amp;#39;s not a great piece of code, but the charge against premature optimization still stands. You &lt;em&gt;don&amp;#39;t&lt;/em&gt; need to get every little ounce of efficiency out of your code. Chances are, if you start guessing at where you can get efficiency, you&amp;#39;re going to be wrong. Measure, measure, measure - profile, profile, profile. Once you&amp;#39;ve done all of that and proved that a change reducing clarity has a significant benefit, go for it - but until then, write the most readable code you can. Likewise work out your performance goals in a &lt;em&gt;meaningful&lt;/em&gt; fashion before you worry too much - and hits per months isn&amp;#39;t a meaningful figure.&lt;/p&gt;  &lt;p&gt;Performance is important - too important to be guessed about instead of measured.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;hr /&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;sup&gt;1&lt;/sup&gt; I&amp;#39;m not linking to it because the Streisand effect would render this question more important than it really is. I&amp;#39;m sure you can find it if you really want to, but that&amp;#39;s not the point of the post.&lt;/p&gt;  &lt;p&gt;&lt;sup&gt;2&lt;/sup&gt; Anyone who wants to nitpick and talk about months which are a bit longer or shorter than that due to daylight saving time changes (despite still being 30 days) can implement that logic for me in Noda Time.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1740046" width="1" height="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><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category></item><item><title>Revisiting randomness</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/11/04/revisiting-randomness.aspx</link><pubDate>Wed, 04 Nov 2009 07:40:15 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1737577</guid><dc:creator>skeet</dc:creator><slash:comments>18</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1737577</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1737577</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/11/04/revisiting-randomness.aspx#comments</comments><description>&lt;p&gt;Almost every Stack Overflow question which includes the words &amp;quot;random&amp;quot; and &amp;quot;repeated&amp;quot; has the same basic answer. It&amp;#39;s one of the most common &amp;quot;gotchas&amp;quot; in .NET, Java, and no doubt other platforms: creating a new random number generator without specifying a seed will depend on the current instant of time. The current time as measured by the computer doesn&amp;#39;t change very often compared with how often you can create and use a random number generator – so code which repeatedly creates a new instance of Random and uses it once will end up showing a lot of repetition.&lt;/p&gt;  &lt;p&gt;One common solution is to use a static field to store a single instance of Random and reuse it. That&amp;#39;s okay in Java (where Random is thread-safe) but it&amp;#39;s not so good in .NET – if you use the same instance repeatedly from .NET, you can corrupt the internal data structures.&lt;/p&gt;  &lt;p&gt;A long time ago, I created a &lt;a href="http://pobox.com/~skeet/csharp/miscutil/usage/staticrandom.html"&gt;StaticRandom class&lt;/a&gt; in &lt;a href="http://pobox.com/~skeet/csharp/miscutil"&gt;MiscUtil&lt;/a&gt; – essentially, it was just a bunch of static methods (to mirror the instance methods found in Random) wrapping a single instance of Random and locking appropriately. This allows you to just call StaticRandom.Next(1, 7) to roll a die, for example. However, it has a couple of problems:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;It doesn&amp;#39;t scale well in a multi-threaded environment. When I originally wrote it, I benchmarked an alternative approach using [ThreadStatic] and at the time, locking won (at least on my computer, which may well have only had a single core). &lt;/li&gt;    &lt;li&gt;It doesn&amp;#39;t provide any way of getting at an instance of Random, other than by using new Random(StaticRandom.Next()). &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The latter point is mostly a problem because it encourages a style of coding where you just use StaticRandom.Next(…) any time you want a random number. This is undoubtedly convenient in some situations, but it goes against the idea of &lt;a href="http://stackoverflow.com/questions/1667516/doesnt-passing-in-parameters-that-should-be-known-implicitly-violate-encapsulati/1667590#1667590"&gt;treating a source of randomness as a service or dependency&lt;/a&gt;. It makes it harder to get repeatability and to see what needs that dependency.&lt;/p&gt;  &lt;p&gt;I could have just added a method generating a new instance into the existing class, but I decided to play with a different approach – going back to per-thread instances, but this time using the &lt;a href="http://msdn.microsoft.com/en-us/library/dd642243(VS.100).aspx"&gt;ThreadLocal&amp;lt;T&amp;gt; class&lt;/a&gt; introduced in .NET 4.0. Here&amp;#39;s the resulting code:&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.Threading;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Namespace"&gt;namespace&lt;/span&gt; RandomDemo     &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;/// Convenience class for dealing with randomness.&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;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; ThreadLocalRandom     &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="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// Random number generator used to generate seeds,&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// which are then used to create new random number&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// generators on a per-thread basis.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&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; Random globalRandom = &lt;span class="Keyword"&gt;new&lt;/span&gt; Random();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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="ReferenceType"&gt;object&lt;/span&gt; globalLock = &lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;object&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="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// Random number generator &lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&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; ThreadLocal&amp;lt;Random&amp;gt; threadRandom = &lt;span class="Keyword"&gt;new&lt;/span&gt; ThreadLocal&amp;lt;Random&amp;gt;(NewRandom);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// Creates a new instance of Random. The seed is derived &lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// from a global (static) instance of Random, rather &lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// than time.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&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; Random NewRandom()     &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;lock&lt;/span&gt; (globalLock)     &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;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; Random(globalRandom.Next());     &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;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// Returns an instance of Random which can be used freely&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// within the current thread.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&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;&amp;#160;&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; Random Instance { get { &lt;span class="Statement"&gt;return&lt;/span&gt; threadRandom.Value; } }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;See &amp;lt;see cref=&amp;quot;Random.Next()&amp;quot; /&amp;gt;&amp;lt;/summary&amp;gt;&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;public&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; 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; &lt;span class="Statement"&gt;return&lt;/span&gt; Instance.Next();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;See &amp;lt;see cref=&amp;quot;Random.Next(int)&amp;quot; /&amp;gt;&amp;lt;/summary&amp;gt;&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;public&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; Next(&lt;span class="ValueType"&gt;int&lt;/span&gt; maxValue)     &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; Instance.Next(maxValue);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;See &amp;lt;see cref=&amp;quot;Random.Next(int, int)&amp;quot; /&amp;gt;&amp;lt;/summary&amp;gt;&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;public&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; Next(&lt;span class="ValueType"&gt;int&lt;/span&gt; minValue, &lt;span class="ValueType"&gt;int&lt;/span&gt; maxValue)     &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; Instance.Next(minValue, maxValue);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;See &amp;lt;see cref=&amp;quot;Random.NextDouble()&amp;quot; /&amp;gt;&amp;lt;/summary&amp;gt;&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;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;double&lt;/span&gt; NextDouble()     &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; Instance.NextDouble();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;See &amp;lt;see cref=&amp;quot;Random.NextBytes(byte[])&amp;quot; /&amp;gt;&amp;lt;/summary&amp;gt;&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;public&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; NextBytes(&lt;span class="ValueType"&gt;byte&lt;/span&gt;[] buffer)     &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; Instance.NextBytes(buffer);     &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;The user can still call the static Next(…) methods if they want, but they can also get at the thread-local instance of Random by calling ThreadLocalRandom.Instance – or easily create a new instance with ThreadLocalRandom.NewRandom(). (The fact that NewRandom uses the global instance rather than the thread-local one is an implementation detail really; it happens to be convenient from the point of view of the ThreadLocal&amp;lt;T&amp;gt; constructor. It wouldn&amp;#39;t be terribly hard to change this.)&lt;/p&gt;  &lt;p&gt;Now it&amp;#39;s easy to write a method which needs randomness (e.g. to shuffle a deck of cards) and give it a Random parameter, then call it using the thread-local instance:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Shuffle(Random rng)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ...     &lt;br /&gt;}     &lt;br /&gt;...     &lt;br /&gt;deck.Shuffle(ThreadLocalRandom.Instance); &lt;/div&gt;  &lt;p&gt;The Shuffle method is then easier to test and debug, and expresses its dependency explicitly.&lt;/p&gt;  &lt;h3&gt;Performance&lt;/h3&gt;  &lt;p&gt;I tested the &amp;quot;old&amp;quot; and &amp;quot;new&amp;quot; implementations in a very simple way – for varying numbers of threads, I called Next() a fixed number of times (from each thread) and timed how long it took for all the threads to finish. I&amp;#39;ve also tried a .NET-3.5-compatible version using ThreadStatic instead of ThreadLocal&amp;lt;T&amp;gt;, and running the original code and the ThreadStatic version on .NET 3.5 as well.&lt;/p&gt;  &lt;table border="1" cellspacing="0" cellpadding="2"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td align="right"&gt;Threads&lt;/td&gt;        &lt;td align="right"&gt;StaticRandom (4.0b2)&lt;/td&gt;        &lt;td align="right"&gt;ThreadLocalRandom (4.0b2)&lt;/td&gt;        &lt;td align="right"&gt;ThreadStaticRandom (4.0b2)&lt;/td&gt;        &lt;td align="right"&gt;StaticRandom(3.5)&lt;/td&gt;        &lt;td align="right"&gt;ThreadStaticRandom (3.5)&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td align="right"&gt;1&lt;/td&gt;        &lt;td align="right"&gt;11582&lt;/td&gt;        &lt;td align="right"&gt;6016&lt;/td&gt;        &lt;td align="right"&gt;10150&lt;/td&gt;        &lt;td align="right"&gt;10373&lt;/td&gt;        &lt;td align="right"&gt;16049&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td align="right"&gt;2&lt;/td&gt;        &lt;td align="right"&gt;24667&lt;/td&gt;        &lt;td align="right"&gt;7214&lt;/td&gt;        &lt;td align="right"&gt;9043&lt;/td&gt;        &lt;td align="right"&gt;25062&lt;/td&gt;        &lt;td align="right"&gt;17257&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td align="right"&gt;3&lt;/td&gt;        &lt;td align="right"&gt;38095&lt;/td&gt;        &lt;td align="right"&gt;10295&lt;/td&gt;        &lt;td align="right"&gt;14771&lt;/td&gt;        &lt;td align="right"&gt;36827&lt;/td&gt;        &lt;td align="right"&gt;25625&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td align="right"&gt;4&lt;/td&gt;        &lt;td align="right"&gt;49402&lt;/td&gt;        &lt;td align="right"&gt;13435&lt;/td&gt;        &lt;td align="right"&gt;19116&lt;/td&gt;        &lt;td align="right"&gt;47882&lt;/td&gt;        &lt;td align="right"&gt;34415&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;A few things to take away from this:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The numbers were slightly erratic; somehow it was quicker to do twice the work with ThreadStaticRandom on .NET 4.0b2! This isn&amp;#39;t the perfect benchmarking machine; we&amp;#39;re interested in trends rather than absolute figures. &lt;/li&gt;    &lt;li&gt;Locking hasn&amp;#39;t changed much in performance between framework versions &lt;/li&gt;    &lt;li&gt;ThreadStatic has improved &lt;em&gt;massively&lt;/em&gt; between .NET 3.5 and 4.0 &lt;/li&gt;    &lt;li&gt;Even on 3.5, ThreadStatic wins over a global lock as soon as there&amp;#39;s contention &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The only downside to the ThreadLocal&amp;lt;T&amp;gt; version is that it requires .NET 4.0 - but the ThreadStatic version works pretty well too.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s worth bearing in mind that of course this is testing the highly unusual situation where there&amp;#39;s a &lt;em&gt;lot&lt;/em&gt; of contention in the global lock version. The performance difference in the single-threaded version where the lock is always uncontended is still present, but very small.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Update&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;After reading the comments and thinking further, I would indeed get rid of the static methods elsewhere. Also, for the purposes of dependency injection, I agree that it&amp;#39;s a good idea to have a factory interface &lt;em&gt;where that&amp;#39;s not overkill&lt;/em&gt;. The factory implementation could use either the ThreadLocal or ThreadStatic implementations, or effectively use the global lock version (by having its own instance of Random and a lock). In many cases I&amp;#39;d regard that as overkill, however.&lt;/p&gt;  &lt;p&gt;One other interesting option would be to create a thread-safe instance of Random to start with, which delegated to thread-local &amp;quot;normal&amp;quot; implementations. That would be very useful from a DI standpoint.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1737577" width="1" height="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/Parallelisation/default.aspx">Parallelisation</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Benchmarking/default.aspx">Benchmarking</category></item><item><title>Iterating atomically</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/10/23/iterating-atomically.aspx</link><pubDate>Fri, 23 Oct 2009 21:20:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1734632</guid><dc:creator>skeet</dc:creator><slash:comments>34</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1734632</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1734632</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/10/23/iterating-atomically.aspx#comments</comments><description>&lt;p&gt;The IEnumerable&amp;lt;T&amp;gt; and IEnumerator&amp;lt;T&amp;gt; interfaces in .NET are interesting. They crop up an awful lot, but hardly anyone ever calls them directly - you almost always use a foreach loop to iterate over the collection. That hides all the calls to GetEnumerator(), MoveNext() and Current. Likewise iterator blocks hide the details when you want to implement the interfaces. However, sometimes details matter - such as for &lt;a href="http://stackoverflow.com/questions/1605745"&gt;this recent Stack Overflow question&lt;/a&gt;. The question asks how to create a thread-safe iterator - one that can be called from multiple threads. This is not about iterating over a collection &lt;em&gt;n&lt;/em&gt; times independently on &lt;em&gt;n&lt;/em&gt; different threads - this is about iterating over a collection &lt;em&gt;once&lt;/em&gt; without skipping or duplicating. Imagine it&amp;#39;s some set of jobs that we have to complete. We assume that the iterator itself is thread-safe to the extent that calls from different threads &lt;em&gt;at different times, with intervening locks&lt;/em&gt; will be handled reasonably. This is reasonable - basically, so long as it isn&amp;#39;t going out of its way to be thread-hostile, we should be okay. We also assume that no-one is trying to write to the collection at the same time.&lt;/p&gt;
&lt;p&gt;Sounds easy, right? Well, no... because the IEnumerator&amp;lt;T&amp;gt; interface has two members which we effectively want to call atomically. In particular, we &lt;em&gt;don&amp;#39;t&lt;/em&gt; want the collection { &amp;quot;a&amp;quot;, &amp;quot;b&amp;quot; } to be iterated like this:&lt;/p&gt;
&lt;table width="400" cellpadding="2" cellspacing="0" border="0"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td width="200" valign="top"&gt;Thread 1&lt;/td&gt;
&lt;td width="200" valign="top"&gt;Thread 2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="200" valign="top"&gt;MoveNext()&lt;/td&gt;
&lt;td width="200" valign="top"&gt;&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="200" valign="top"&gt;&amp;nbsp;&lt;/td&gt;
&lt;td width="200" valign="top"&gt;MoveNext()&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="200" valign="top"&gt;Current&lt;/td&gt;
&lt;td width="200" valign="top"&gt;&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="200" valign="top"&gt;&amp;nbsp;&lt;/td&gt;
&lt;td width="200" valign="top"&gt;Current&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;That way we&amp;#39;ll end up not processing the first item at all, and the second item twice.&lt;/p&gt;
&lt;p&gt;There are two ways of approaching this problem. In both cases I&amp;#39;ve started with IEnumerable&amp;lt;T&amp;gt; for consistency, but in fact it&amp;#39;s IEnumerator&amp;lt;T&amp;gt; which is the interesting bit. In particular, we&amp;#39;re not going to be able to iterate over our result anyway, as each thread needs to have the same IEnumerator&amp;lt;T&amp;gt; - which it won&amp;#39;t do if each of them uses foreach (which calls GetEnumerator() to start with).&lt;/p&gt;
&lt;h3&gt;Fix the interface&lt;/h3&gt;
&lt;p&gt;First we&amp;#39;ll try to fix the interface to look how it should have looked to start with, at least from the point of view of atomicity. Here are the new interfaces:&lt;/p&gt;
&lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; IAtomicEnumerable&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IAtomicEnumerator&amp;lt;T&amp;gt; GetEnumerator();     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; IAtomicEnumerator&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ValueType"&gt;bool&lt;/span&gt; TryMoveNext(&lt;span class="MethodParameter"&gt;out&lt;/span&gt; T nextValue);     &lt;br /&gt;} &lt;/div&gt;
&lt;p&gt;One thing you may notice is that we&amp;#39;re not implementing IDisposable. That&amp;#39;s basically because it&amp;#39;s a pain to do so when you think about a multi-threaded environment. Indeed, it&amp;#39;s possibly one of the biggest arguments against something of this nature. At what point do you dispose? Just because &lt;em&gt;one&lt;/em&gt; thread finished doesn&amp;#39;t mean that the rest of them have... don&amp;#39;t forget that &amp;quot;finish&amp;quot; might mean &amp;quot;an exception was thrown while processing the job, I&amp;#39;m bailing out&amp;quot;. You&amp;#39;d need some sort of co-ordinator to make sure that &lt;em&gt;everyone&lt;/em&gt; is finished before you actually do any clean-up. Anyway, the nice thing about this being a blog post is we can ignore that little thorny issue :)&lt;/p&gt;
&lt;p&gt;The important point is that we now have a single method in IAtomicEnumerator&amp;lt;T&amp;gt; - TryMoveNext, which works the way you&amp;#39;d expect it to. It atomically attempts to move to the next item, returns whether or not it succeeded, and sets an out parameter with the next value if it &lt;em&gt;did&lt;/em&gt; succeed. Now there&amp;#39;s no chance of two threads using the method and stomping on each other&amp;#39;s values (unless they&amp;#39;re silly and use the same variable for the out parameter).&lt;/p&gt;
&lt;p&gt;It&amp;#39;s reasonably easy to wrap the standard interfaces in order to implement this interface:&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;/// Wraps a normal IEnumerable[T] up to implement IAtomicEnumerable[T].&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;public&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; AtomicEnumerable&amp;lt;T&amp;gt; : IAtomicEnumerable&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; original;     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; AtomicEnumerable(IEnumerable&amp;lt;T&amp;gt; original)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Keyword"&gt;this&lt;/span&gt;.original = original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; IAtomicEnumerator&amp;lt;T&amp;gt; GetEnumerator()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt; AtomicEnumerator(original.GetEnumerator());     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="XmlComment"&gt;/// Implementation of IAtomicEnumerator[T] to wrap IEnumerator[T].&lt;/span&gt;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; AtomicEnumerator : IAtomicEnumerator&amp;lt;T&amp;gt;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; IEnumerator&amp;lt;T&amp;gt; original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;object&lt;/span&gt; padlock = &lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;object&lt;/span&gt;();     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;internal&lt;/span&gt; AtomicEnumerator(IEnumerator&amp;lt;T&amp;gt; original)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Keyword"&gt;this&lt;/span&gt;.original = original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;bool&lt;/span&gt; TryMoveNext(&lt;span class="MethodParameter"&gt;out&lt;/span&gt; T value)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;lock&lt;/span&gt; (padlock)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ValueType"&gt;bool&lt;/span&gt; hadNext = original.MoveNext();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; value = hadNext ? original.Current : &lt;span class="Modifier"&gt;default&lt;/span&gt;(T);     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt; hadNext;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;} &lt;/div&gt;
&lt;p&gt;Just ignore the fact that I never dispose of the original IEnumerator&amp;lt;T&amp;gt; :)&lt;/p&gt;
&lt;p&gt;We use a simple lock to make sure that MoveNext() and Current always happen together - that nothing else is going to call MoveNext() between our TryMoveNext() calling it, and it fetching the current value.&lt;/p&gt;
&lt;p&gt;Obviously you&amp;#39;d need to write your own code to actually &lt;em&gt;use&lt;/em&gt; this sort of iterator, but it would be quite simple:&lt;/p&gt;
&lt;div class="code"&gt;T value;    &lt;br /&gt;&lt;span class="Statement"&gt;while&lt;/span&gt; (iterator.TryMoveNext(&lt;span class="MethodParameter"&gt;out&lt;/span&gt; value))     &lt;br /&gt;{     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="InlineComment"&gt;// Use value&lt;/span&gt;     &lt;br /&gt;} &lt;/div&gt;
&lt;p&gt;However, you may already have code which wants to use an IEnumerator&amp;lt;T&amp;gt;. Let&amp;#39;s see what else we can do.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Using thread local variables to fake it&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;.NET 4.0 has a very useful type called ThreadLocal&amp;lt;T&amp;gt;. It does basically what you&amp;#39;d expect it to, with nice features such as being able to supply a delegate to be executed on each thread to provide the initial value. We can use a thread local to make sure that so long as we call both MoveNext() and Current atomically when we&amp;#39;re asked to move to the next element, we can get back the right value for Current later on. It has to be thread local because we&amp;#39;re sharing a single IEnumerator&amp;lt;T&amp;gt; across multiple threads - each needs its own separate storage.&lt;/p&gt;
&lt;p&gt;This is also the approach we&amp;#39;d use if we wanted to wrap an IAtomicEnumerator&amp;lt;T&amp;gt; in an IEnumerator&amp;lt;T&amp;gt;, by the way. Here&amp;#39;s the code to do it:&lt;/p&gt;
&lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; ThreadSafeEnumerable&amp;lt;T&amp;gt; : IEnumerable&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; original;     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; ThreadSafeEnumerable(IEnumerable&amp;lt;T&amp;gt; original)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Keyword"&gt;this&lt;/span&gt;.original = original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; IEnumerator&amp;lt;T&amp;gt; GetEnumerator()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt; ThreadSafeEnumerator(original.GetEnumerator());     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IEnumerator IEnumerable.GetEnumerator()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt; GetEnumerator();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; ThreadSafeEnumerator : IEnumerator&amp;lt;T&amp;gt;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; IEnumerator&amp;lt;T&amp;gt; original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;object&lt;/span&gt; padlock = &lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;object&lt;/span&gt;();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; ThreadLocal&amp;lt;T&amp;gt; current = &lt;span class="Keyword"&gt;new&lt;/span&gt; ThreadLocal&amp;lt;T&amp;gt;();     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;internal&lt;/span&gt; ThreadSafeEnumerator(IEnumerator&amp;lt;T&amp;gt; original)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Keyword"&gt;this&lt;/span&gt;.original = original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;bool&lt;/span&gt; MoveNext()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;lock&lt;/span&gt; (padlock)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ValueType"&gt;bool&lt;/span&gt; ret = original.MoveNext();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;if&lt;/span&gt; (ret)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; current.Value = original.Current;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt; ret;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; T Current     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; get { &lt;span class="Statement"&gt;return&lt;/span&gt; current.Value; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;void&lt;/span&gt; Dispose()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; original.Dispose();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; current.Dispose();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ReferenceType"&gt;object&lt;/span&gt; IEnumerator.Current     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; get { &lt;span class="Statement"&gt;return&lt;/span&gt; Current; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;void&lt;/span&gt; Reset()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt; NotSupportedException();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;} &lt;/div&gt;
&lt;p&gt;I&amp;#39;m going to say it one last time - we&amp;#39;re broken when it comes to disposal. There&amp;#39;s no way of &lt;em&gt;safely&lt;/em&gt; disposing of the original iterator at &amp;quot;just the right time&amp;quot; when everyone&amp;#39;s finished with it. Oh well.&lt;/p&gt;
&lt;p&gt;Other than that, it&amp;#39;s quite simple. This code has the serendipitous property of actually implementing IEnumerator&amp;lt;T&amp;gt; slightly better than C#-compiler-generated implementations from iterator blocks - if you call the Current property without having called MoveNext(), this will throw an InvalidOperationException, just as the documentation says it should. (It doesn&amp;#39;t do the same at the end, admittedly, but that&amp;#39;s fixable if we really wanted to be pedantic.&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;I found this an intriguing little problem. I think there are better ways of solving the bigger picture - a co-ordinator which takes care of disposing exactly once, and which possibly mediates the original iterator etc is probably the way forward... but I enjoyed thinking about the nitty gritty.&lt;/p&gt;
&lt;p&gt;Generally speaking, I prefer the first of these approaches. Thread local variables always feel like a bit of a grotty hack to me - they can be useful, but it&amp;#39;s better to avoid them if you can. It&amp;#39;s interesting to see how an interface can be inherently thread-friendly or not.&lt;/p&gt;
&lt;p&gt;One last word of warning - this code is &lt;em&gt;completely&lt;/em&gt; untested. It builds, and I can&amp;#39;t immediately see why it wouldn&amp;#39;t work, but I&amp;#39;m making no guarantees...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1734632" width="1" height="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/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Parallelisation/default.aspx">Parallelisation</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category></item><item><title>API design: choosing between non-ideal options</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/09/14/api-design-choosing-between-non-ideal-options.aspx</link><pubDate>Mon, 14 Sep 2009 16:38:05 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1723277</guid><dc:creator>skeet</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1723277</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1723277</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/09/14/api-design-choosing-between-non-ideal-options.aspx#comments</comments><description>&lt;p&gt;So, &lt;a href="http://code.google.com/p/unconstrained-melody"&gt;UnconstrainedMelody&lt;/a&gt; is coming on quite nicely. It now has quite a few useful options for flags enums, &amp;quot;normal enums&amp;quot; and delegates. However, there are two conflicting limitations which leave a couple of options. (Other related answers on Stack Overflow have suggested alternative approaches, basically.)&lt;/p&gt;  &lt;p&gt;Currently, most of the enums code is in two classes: Flags and Enums. Both are non-generic: the methods within them are generic methods, so they have type parameters (and constraints). The main benefit of this is that generic type inference only applies to generic methods, and I &lt;em&gt;definitely&lt;/em&gt; want that for extension methods and anywhere else it makes sense.&lt;/p&gt;  &lt;p&gt;The drawback is that properties can&amp;#39;t be generic. That means my API is entirely expressed in terms of methods, which can be a pain. The option to work around this is to have a generic type which properties in. This adds confusion and guesswork - what call is where?&lt;/p&gt;  &lt;p&gt;To recap, the options are:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Option 1 (current): all methods in a nongeneric class:&lt;/span&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Some calls which are logically properties end up&lt;/span&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// as methods...&lt;/span&gt;    &lt;br /&gt;IList&amp;lt;Foo&amp;gt; foos = Enums.GetValues&amp;lt;Foo&amp;gt;();    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Type infererence for extenion methods&lt;/span&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Note that we couldn&amp;#39;t have a Description property&lt;/span&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// as we don&amp;#39;t have extension properties&lt;/span&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; firstDescription = foos[0].GetDescription();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&lt;span class="InlineComment"&gt;// Option 2: Use just a generic type:&lt;/span&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Now we can use a property...&lt;/span&gt;    &lt;br /&gt;IList&amp;lt;Foo&amp;gt; foos = Enums&amp;lt;Foo&amp;gt;.Values;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// But we can&amp;#39;t use type inference&lt;/span&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; firstDescription = Enums&amp;lt;Foo&amp;gt;.GetDescription(foos[0]);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&lt;span class="InlineComment"&gt;// Option 3: Use a mixture (Enums and Enums&amp;lt;T&amp;gt;):&lt;/span&gt;    &lt;br /&gt;IList&amp;lt;Foo&amp;gt; foos = Enums&amp;lt;Foo&amp;gt;.Values;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// All looks good...&lt;/span&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; firstDescription = foos[0].GetDescription();    &lt;br /&gt;&lt;span class="InlineComment"&gt;// ... but the user has to know when to use which class&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;All of these are somewhat annoying. If we &lt;em&gt;only &lt;/em&gt;put extension methods into the nongeneric class, then I guess users would never need to really think about that - they&amp;#39;d pretty much always be calling the methods via the extension method syntactic sugar anyway. It still feels like a pretty arbitrary split though.&lt;/p&gt;  &lt;p&gt;Any thoughts? Which is more important - conceptual complexity, or the idiomatic client code you end up with once that complexity has been mastered? Is it reasonable to make design decisions like this around what is essentially a single piece of syntactic sugar (extension methods)?&lt;/p&gt;  &lt;p&gt;(By the way, if anyone ever wanted justification for extension properties, I think this is a good example... Description feels like it really &lt;em&gt;should&lt;/em&gt; be a property.)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1723277" width="1" height="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/Stack+Overflow/default.aspx">Stack Overflow</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Evil+Code/default.aspx">Evil Code</category></item><item><title>Generic constraints for enums and delegates</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx</link><pubDate>Thu, 10 Sep 2009 20:09:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1722426</guid><dc:creator>skeet</dc:creator><slash:comments>56</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1722426</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1722426</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx#comments</comments><description>&lt;p&gt;As most readers probably know, C# prohibits generic type constraints from referring to System.Object, System.Enum, System.Array, System.Delegate and System.ValueType. In other words, this method declaration is illegal:&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; T[] GetValues&amp;lt;T&amp;gt;() &lt;span class="Linq"&gt;where&lt;/span&gt; T : struct, System.Enum    &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; (T[]) Enum.GetValues(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(T));     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;This is a pity, as such a method could be useful. (In fact there are better things we can do... such as returning a read-only collection. That way we don&amp;#39;t have to create a new array each time the method is called.) As far as I can tell, there is no reason why this should be prohibited. Eric Lippert has stated that he believes &lt;a href="http://stackoverflow.com/questions/1331739/enum-type-constraints-in-c/1331811#1331811"&gt;the CLR doesn&amp;#39;t support this&lt;/a&gt; - but I think he&amp;#39;s wrong. I can&amp;#39;t remember the last time I had cause to believe Eric to be wrong about something, and I&amp;#39;m somewhat nervous of even mentioning it, but section 10.1.7 of the CLI spec (&lt;a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm"&gt;ECMA-335&lt;/a&gt;) partition II (p40) &lt;em&gt;specifically&lt;/em&gt; gives examples of type parameter constraints involving System.Delegate and System.Enum. It introduces the table with &amp;quot;The following table shows the valid combinations of type and special constraints for a representative set of types.&amp;quot; It was only due to reading this table that I realized that the value type constraint on the above is required (or a constructor constraint would do equally well) - otherwise System.Enum itself satisfies the constraint, which would be a Bad Thing.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s possible (but unlikely) that the CLI doesn&amp;#39;t fully implement this part of the CLR spec. I&amp;#39;m hoping that Eric&amp;#39;s just wrong on this occasion, and that actually there&amp;#39;s nothing to stop the C# language from allowing such constraints in the future. (It would be nice to get keyword support, such that a constraint of &amp;quot;T : enum&amp;quot; would be equivalent to the above, but hey...)&lt;/p&gt;  &lt;p&gt;The good news is that ilasm/ildasm have no problem with this. The better news is that if you add a reference to a library which uses those constraints, the C# compiler applies them sensibly, as far as I can tell...&lt;/p&gt;  &lt;h3&gt;Introducing UnconstrainedMelody&lt;/h3&gt;  &lt;p&gt;(Okay, the name will almost surely have to change. But I like the idea of it removing the constraints of C# around which constraints are valid... and yet still being in the key of C#. Better suggestions welcome.)&lt;/p&gt;  &lt;p&gt;I have a plan - I want to write a utility library which does useful things for enums and delegates (and arrays if I can think of anything sensible to do with them). It will be written in C#, with methods like this:&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; T[] GetValues&amp;lt;T&amp;gt;() &lt;span class="Linq"&gt;where&lt;/span&gt; T : struct, IEnumConstraint    &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; (T[]) Enum.GetValues(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(T));     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;(IEnumConstraint has to be an interface of course, as otherwise the constraint would be invalid.)&lt;/p&gt;  &lt;p&gt;As a post-build step, I will:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Run ildasm on the resulting binary &lt;/li&gt;    &lt;li&gt;Replace every constraint using EnumConstraint with System.Enum &lt;/li&gt;    &lt;li&gt;Run ilasm to build the binary again &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;If anyone has a &lt;em&gt;simple&lt;/em&gt; binary rewriter (I&amp;#39;ve looked at &lt;a href="http://postsharp.org"&gt;PostSharp&lt;/a&gt; and &lt;a href="http://cciast.codeplex.com/license"&gt;CCI&lt;/a&gt;; both look &lt;em&gt;way&lt;/em&gt; more complicated than the above) which would do this, that would be great. Otherwise ildasm/ilasm will be fine. It&amp;#39;s not like &lt;em&gt;consumers&lt;/em&gt; will need to perform this step.&lt;/p&gt;  &lt;p&gt;As soon as the name is finalized I&amp;#39;ll add a project on Google Code. Once the infrastructure is in place, adding utility methods should be very straightforward. Suggestions for utility methods would be useful, or just join the project when it&amp;#39;s up and running.&lt;/p&gt;  &lt;p&gt;Am I being silly? Have I overlooked something?&lt;/p&gt;  &lt;h3&gt;A couple of hours later...&lt;/h3&gt;  &lt;p&gt;Okay, I decided not to wait for a better name. The first cut - which does basically nothing but validate the idea, and the fact that I can still unit test it - is in. The &lt;a href="http://code.google.com/p/unconstrained-melody"&gt;UnconstrainedMelody Google Code project&lt;/a&gt; is live!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1722426" width="1" height="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/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category></item><item><title>Recent activities</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/09/04/recent-activities.aspx</link><pubDate>Thu, 03 Sep 2009 23:08:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1720570</guid><dc:creator>skeet</dc:creator><slash:comments>15</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1720570</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1720570</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/09/04/recent-activities.aspx#comments</comments><description>&lt;p&gt;It&amp;#39;s been a little while since I&amp;#39;ve blogged, and quite a lot has been going on. In fact, there are a few things I&amp;#39;d have blogged about already if it weren&amp;#39;t for &amp;quot;things&amp;quot; getting in the way.&lt;/p&gt;
&lt;p&gt;Rather than writing a whole series of very short blog posts, I thought I&amp;#39;d wrap them all up here...&lt;/p&gt;
&lt;h3&gt;C# in Depth: next MEAP drop available soon - Code Contracts&lt;/h3&gt;
&lt;p&gt;Thanks to everyone who gave feedback on my &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2009/08/05/tricky-decisions-code-contracts-and-parallel-extensions-in-c-in-depth-2nd-edition.aspx"&gt;writing dilemma&lt;/a&gt;. For the moment, the plan is to have a whole chapter about Code Contracts, but &lt;em&gt;not&lt;/em&gt; include a chapter about Parallel Extensions. My argument for making this decision is that Code Contracts really change the &lt;em&gt;feel&lt;/em&gt; of the code, making it almost like a language feature - and its applicability is almost ubiquitous, unlike PFX.&lt;/p&gt;
&lt;p&gt;I &lt;em&gt;may&lt;/em&gt; write a PFX chapter as a separate download, but I&amp;#39;m sensitive to those who (like me) appreciate slim books. I don&amp;#39;t want to &amp;quot;bulk out&amp;quot; the book with extra topics.&lt;/p&gt;
&lt;p&gt;The Code Contracts chapter is in the final stages before becoming available to MEAP subscribers. (It&amp;#39;s been &amp;quot;nearly ready&amp;quot; for a couple of weeks, but I&amp;#39;ve been on holiday, amongst other things.) After that, I&amp;#39;m going back to the existing chapters and revising them.&lt;/p&gt;
&lt;h3&gt;Talking in Dublin - C# 4 and Parallel Extensions&lt;/h3&gt;
&lt;p&gt;Last week I gave two talks in Dublin at &lt;a href="http://epicenter.ie/"&gt;Epicenter&lt;/a&gt;. One was on C# 4, and the other on Code Contracts and Parallel Extensions. Both are now available in a slightly odd form on the &lt;a href="http://csharpindepth.com/Talks.aspx"&gt;Talks page&lt;/a&gt; of the C# in Depth web site. I no longer write &amp;quot;formal&amp;quot; PowerPoint slides, so the downloads are for simple bullet points of text, along with silly hand-drawn slides. No code yet - I want to tidy it up a bit before including it.&lt;/p&gt;
&lt;h3&gt;Podcasting with The Connected Show&lt;/h3&gt;
&lt;p&gt;I recently recorded a &lt;a href="http://www.lyalin.com/Blog/archive/2009/09/01/connected-show-15-ndash-c-4-it-ainrsquot-that-complex.aspx"&gt;podcast episode&lt;/a&gt; with &lt;a href="http://www.connectedshow.com/"&gt;The Connected Show&lt;/a&gt;. I&amp;#39;m &amp;quot;on&amp;quot; for the second 2/3 of the show - about an hour of me blathering on about the new features of C# 4. If you can understand generic variance just by listening to me talking about it, you&amp;#39;re a smart cookie ;)&lt;/p&gt;
&lt;p&gt;(Oh, and if you like it, please express your amusement on &lt;a href="http://digg.com/microsoft/Connected_Show_15_Jon_Skeet_goes_DEEP_on_C_4_0"&gt;Digg&lt;/a&gt; / &lt;a href="http://www.dzone.com/links/connected_show_15_jon_skeet_goes_deep_on_c_40.html"&gt;DZone&lt;/a&gt; / &lt;a href="http://dotnetshoutout.com/Connected-Show-15-Jon-Skeet-goes-DEEP-on-C-40"&gt;Shout&lt;/a&gt; / &lt;a href="http://www.dotnetkicks.com/csharp/Connected_Show_15_Jon_Skeet_goes_DEEP_on_C_4_0"&gt;Kicks&lt;/a&gt;.)&lt;/p&gt;
&lt;h3&gt;Finishing up with Functional Programming for the Real World&lt;/h3&gt;
&lt;p&gt;Well, this hasn&amp;#39;t been taking much of my time recently (I bowed out of all the indexing etc!) but &lt;a href="http://manning.com/petricek"&gt;Functional Programming for the Real World&lt;/a&gt; is nearly ready to go. Hard copy should be available in the next couple of months... it&amp;#39;ll be really nice to see how it fares. Much kudos to Tomas for all his hard work - I&amp;#39;ve really just been helping out a little.&lt;/p&gt;
&lt;h3&gt;Starting on Groovy in Action, 2nd edition&lt;/h3&gt;
&lt;p&gt;No sooner does one book finish than another one starts. The &lt;a href="http://manning.com/koenig2/"&gt;second edition of Groovy in Action&lt;/a&gt; is in the works, which should prove interesting. To be honest, I haven&amp;#39;t played with Groovy much since the first edition of the book was finished, so it&amp;#39;ll be interesting to see what&amp;#39;s happened to the language in the meantime. I&amp;#39;ll be applying the same sort of spit and polish that I did in the first edition, and asking appropriately ignorant questions of the other authors.&lt;/p&gt;
&lt;h3&gt;Tech Reviewing C# 4.0 in a Nutshell&lt;/h3&gt;
&lt;p&gt;&lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2008/03/31/book-review-c-3-0-in-a-nutshell.aspx"&gt;I liked C# 3.0 in a Nutshell&lt;/a&gt;, and I feel honoured that Joe asked me to be a tech reviewer for the next edition, which promises to be even better. There&amp;#39;s not a lot more I can say about it at the moment, other than it&amp;#39;ll be out in 2010 - and I still feel that C# in Depth is a good companion book.&lt;/p&gt;
&lt;h3&gt;MoreLINQ now at 1.0 beta&lt;/h3&gt;
&lt;p&gt;A while ago I started the &lt;a href="http://code.google.com/p/morelinq/"&gt;MoreLINQ project&lt;/a&gt;, and it gained some developers with more time than I&amp;#39;ve got available :) Basically the idea is to add some more useful LINQ extension methods to LINQ to Object. Thanks to Atif Aziz, the first beta version has been released. This doesn&amp;#39;t mean we&amp;#39;re &amp;quot;done&amp;quot; though - just that we think we&amp;#39;ve got something useful. Any suggestions for other operators would be welcome.&lt;/p&gt;
&lt;h3&gt;Manning Pop Quiz and discounts&lt;/h3&gt;
&lt;p&gt;While I&amp;#39;m plugging books etc, it&amp;#39;s worth mentioning the &lt;a href="http://www.manning.com/popquiz/"&gt;Manning Pop Quiz&lt;/a&gt; - multiple choice questions on a wide variety of topics. Fabulous prizes available, as well as one-day discounts:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Monday, Sept 7th: 50% of all print books (code: pop0907)&lt;/li&gt;
&lt;li&gt;Monday, Sept 14: 50% off all ebooks&amp;nbsp; (code: pop0914)&lt;/li&gt;
&lt;li&gt;Thursday, Sept 17: $25 for C# in Depth, 2nd Edition MEAP print version (code: pop0917) + C# Pop Quiz question&lt;/li&gt;
&lt;li&gt;Monday, Sept 21: 50% off all books&amp;nbsp; (code: pop0921)&lt;/li&gt;
&lt;li&gt;Thursday, Sept 24: $12 for C# in Depth, 2nd Edition MEAP ebook (code: pop0924) + another C# Pop Quiz question&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Future speaking engagements&lt;/h3&gt;
&lt;p&gt;On September 16th I&amp;#39;m going to be speaking to &lt;a href="http://edgeug.net/"&gt;Edge UG&lt;/a&gt; (formerly Vista Squad) in London about Code Contracts and Parallel Extensions. I&amp;#39;m already &lt;em&gt;very&lt;/em&gt; much looking forward to the &lt;a href="http://stackoverflow.carsonified.com/events/london/"&gt;Stack Overflow DevDays London conference&lt;/a&gt; on October 28th, at which I&amp;#39;ll be talking about how humanity has screwed up computing.&lt;/p&gt;
&lt;h3&gt;Future potential blog posts&lt;/h3&gt;
&lt;p&gt;Some day I may get round to writing about:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Revisiting StaticRandom with ThreadLocal&amp;lt;T&amp;gt;&lt;/li&gt;
&lt;li&gt;Volatile doesn&amp;#39;t mean what I thought it did&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There&amp;#39;s a lot more writing than coding in that list... I&amp;#39;d like to spend some more time on &lt;a href="http://code.google.com/p/minibench/"&gt;MiniBench&lt;/a&gt; at some point, but you know what deadlines are like.&lt;/p&gt;
&lt;p&gt;Anyway, that&amp;#39;s what I&amp;#39;ve been up to and what I&amp;#39;ll be doing for a little while...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1720570" width="1" height="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><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_+4/default.aspx">C# 4</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Parallelisation/default.aspx">Parallelisation</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Speaking+engagements/default.aspx">Speaking engagements</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category></item><item><title>Faking COM to fool the C# compiler</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/07/07/faking-com-to-fool-the-c-compiler.aspx</link><pubDate>Tue, 07 Jul 2009 22:28:46 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1698645</guid><dc:creator>skeet</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1698645</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1698645</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/07/07/faking-com-to-fool-the-c-compiler.aspx#comments</comments><description>&lt;p&gt;C# 4 has some great features to make programming against COM components &lt;strike&gt;bearable&lt;/strike&gt; fun and exciting. In particular:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;PIA linking allows you to embed just the relevant bits of the Primary Interop Assembly into your own assembly, so the PIA isn&amp;#39;t actually required at execution time &lt;/li&gt;    &lt;li&gt;Named arguments and optional parameters make life &lt;em&gt;much&lt;/em&gt; simpler for APIs like Office which are full of methods with gazillions of parameters &lt;/li&gt;    &lt;li&gt;&amp;quot;ref&amp;quot; removal allows you to pass an argument by value even though the parameter is a by-reference parameter (COM only, folks - don&amp;#39;t worry!) &lt;/li&gt;    &lt;li&gt;Dynamic typing allows you to remove a load of casts by converting every parameter and return type of &amp;quot;object&amp;quot; into &amp;quot;dynamic&amp;quot; (if you&amp;#39;re using PIA linking) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I&amp;#39;m currently writing about these features for &lt;a href="http://manning.com/skeet2"&gt;the book&lt;/a&gt; (don&amp;#39;t forget to &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2009/07/06/books-going-cheap.aspx"&gt;buy it cheap on Friday&lt;/a&gt;) but I&amp;#39;m not really a COM person. I want to be able to see these compiler features at work against a really simple type. Unfortunately, these really are COM-specific features... so we&amp;#39;re going to have to persuade COM that the type really is a COM type.&lt;/p&gt;  &lt;p&gt;I got slightly stuck on this first, but thanks to &lt;a href="http://stackoverflow.com/questions/1093536"&gt;the power of Stack Overflow&lt;/a&gt;, I now have a reasonably complete demo &amp;quot;fake&amp;quot; COM type. It doesn&amp;#39;t do a lot, and in particular it doesn&amp;#39;t have any events, but it&amp;#39;s enough to show the compiler features:&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.Runtime.InteropServices;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Required for linking into another assembly (C# 4)&lt;/span&gt;     &lt;br /&gt;[assembly:Guid(&lt;span class="String"&gt;&amp;quot;86ca55e4-9d4b-462b-8ec8-b62e993aeb64&amp;quot;&lt;/span&gt;)]     &lt;br /&gt;[assembly:ImportedFromTypeLib(&lt;span class="String"&gt;&amp;quot;fake.tlb&amp;quot;&lt;/span&gt;)]     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Namespace"&gt;namespace&lt;/span&gt; FakeCom     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [Guid(&lt;span class="String"&gt;&amp;quot;c3cb8098-0b8f-4a9a-9772-788d340d6ae0&amp;quot;&lt;/span&gt;)]     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [ComImport, CoClass(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(FakeImpl))]     &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;interface&lt;/span&gt; FakeComponent     &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="ReferenceType"&gt;object&lt;/span&gt; MakeMeDynamic(&lt;span class="ReferenceType"&gt;object&lt;/span&gt; arg);     &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="ValueType"&gt;void&lt;/span&gt; Foo([Optional] &lt;span class="MethodParameter"&gt;ref&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; x,     &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; [Optional] &lt;span class="MethodParameter"&gt;ref&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; y);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [Guid(&lt;span class="String"&gt;&amp;quot;734e6105-a20f-4748-a7de-2c83d7e91b04&amp;quot;&lt;/span&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;class&lt;/span&gt; FakeImpl {}     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;We have an interface representing our COM type, and a class which the interface claims will implement it. Fortunately the compiler doesn&amp;#39;t actually check that, so we can get away with leaving it entirely unimplemented. It&amp;#39;s also worth noting that our optional parameters can be by-reference parameters (which you can&amp;#39;t normally do in C# 4) and we haven&amp;#39;t given them any default values (as those are ignored for COM anyway).&lt;/p&gt;  &lt;p&gt;This is compiled just like any other assembly: &lt;/p&gt;  &lt;div class="code"&gt;csc /target:library FakeCom.cs &lt;/div&gt;  &lt;p&gt;Then we get to use it with a test program: &lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; FakeCom;    &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="InlineComment"&gt;// Yes, that is calling a &amp;quot;constructor&amp;quot; on an interface&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; FakeComponent com = &lt;span class="Keyword"&gt;new&lt;/span&gt; FakeComponent();    &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;// The boring old fashioned way of calling a method&lt;/span&gt;    &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; i = 0;    &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; j = &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; com.Foo(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; i, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt; j);    &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;// Look ma, no ref!&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; com.Foo(10, &lt;span class="String"&gt;&amp;quot;Wow!&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;// Who cares about parameter ordering?&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; com.Foo(y: &lt;span class="String"&gt;&amp;quot;Not me&amp;quot;&lt;/span&gt;, x: 0);    &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;// And the parameters are optional too&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; com.Foo();    &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;// The line below only works when linked rather than&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;// referenced, as otherwise you need a cast.&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;// The compiler treats it as if it both takes and&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;// returns a dynamic value.&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; value = com.MakeMeDynamic(10);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;This is compiled either in the old &amp;quot;deploy the PIA as well&amp;quot; way (after adding a cast in the last line): &lt;/p&gt;  &lt;div class="code"&gt;csc /r:FakeCom.dll Test.cs &lt;/div&gt;  &lt;p&gt;... or by linking the PIA instead:&lt;/p&gt;  &lt;div class="code"&gt;csc /l:FakeCom.dll Test.cs &lt;/div&gt;  &lt;p&gt;(The difference is just using &lt;code&gt;/l&lt;/code&gt; instead of &lt;code&gt;/r&lt;/code&gt;.)&lt;/p&gt;  &lt;p&gt;When the test code is compiled as a reference, it decompiles in Reflector to this (I&amp;#39;ve added whitespace for clarity):&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="ValueType"&gt;void&lt;/span&gt; Main()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; FakeComponent component = (FakeComponent) &lt;span class="Keyword"&gt;new&lt;/span&gt; FakeImpl();    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; x = 0;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; y = &lt;span class="Keyword"&gt;null&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; component.Foo(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; x, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt; y);    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; num2 = 10;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; str3 = &lt;span class="String"&gt;&amp;quot;Wow!&amp;quot;&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; component.Foo(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; num2, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt; str3);    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; str4 = &lt;span class="String"&gt;&amp;quot;Not me&amp;quot;&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; num3 = 0;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; component.Foo(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; num3, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt; str4);    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; num4 = 0;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; str5 = &lt;span class="Keyword"&gt;null&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; component.Foo(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; num4, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt; str5);    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; str2 = (&lt;span class="ReferenceType"&gt;string&lt;/span&gt;) component.MakeMeDynamic(10);    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Note how the compiler has created local variables to pass by reference; any changes to the parameter are ignored when the method returns. (If you actually pass a variable by reference, the compiler won&amp;#39;t take that away, however.) &lt;/p&gt;  &lt;p&gt;When the code is linked instead, the middle section is the same, but the construction and the line calling &lt;code&gt;MakeMeDynamic&lt;/code&gt; are very different:&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="ValueType"&gt;void&lt;/span&gt; Main()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; FakeComponent component = (FakeComponent) Activator.CreateInstance(Type.GetTypeFromCLSID    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; (&lt;span class="Keyword"&gt;new&lt;/span&gt; Guid(&lt;span class="String"&gt;&amp;quot;734E6105-A20F-4748-A7DE-2C83D7E91B04&amp;quot;&lt;/span&gt;)));    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Middle bit as before&lt;/span&gt;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (&amp;lt;Main&amp;gt;o__SiteContainer6.&amp;lt;&amp;gt;p__Site7 == &lt;span class="Keyword"&gt;null&lt;/span&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; &amp;lt;Main&amp;gt;o__SiteContainer6.&amp;lt;&amp;gt;p__Site7 = CallSite&amp;lt;Func&amp;lt;CallSite, &lt;span class="ReferenceType"&gt;object&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;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; .Create(&lt;span class="Keyword"&gt;new&lt;/span&gt; CSharpConvertBinder    &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; (&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(&lt;span class="ReferenceType"&gt;string&lt;/span&gt;),&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CSharpConversionKind.ImplicitConversion, &lt;span class="Keyword"&gt;false&lt;/span&gt;));    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; str2 = &amp;lt;Main&amp;gt;o__SiteContainer6.&amp;lt;&amp;gt;p__Site7.Target.Invoke    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; (&amp;lt;Main&amp;gt;o__SiteContainer6.&amp;lt;&amp;gt;p__Site7, component.MakeMeDynamic(10));    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The interface is embedded in the generated assembly, but with a slightly different set of attributes:&lt;/p&gt;  &lt;div class="code"&gt;[ComImport, CompilerGenerated]   &lt;br /&gt;[Guid(&lt;span class="String"&gt;&amp;quot;C3CB8098-0B8F-4A9A-9772-788D340D6AE0&amp;quot;&lt;/span&gt;), TypeIdentifier]    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; FakeComponent    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;object&lt;/span&gt; MakeMeDynamic(&lt;span class="ReferenceType"&gt;object&lt;/span&gt; arg);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;void&lt;/span&gt; Foo([Optional] &lt;span class="MethodParameter"&gt;ref&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; x, [Optional] &lt;span class="MethodParameter"&gt;ref&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; y);    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The class isn&amp;#39;t present at all.&lt;/p&gt;  &lt;p&gt;I should point out that doing this has no practical benefit in real code - but the ability to mess around with a pseudo-COM type rather than having to find a &lt;em&gt;real&lt;/em&gt; one with the exact members I want will make it a lot easier to try a few corner cases for the book.&lt;/p&gt;  &lt;p&gt;So, not a terribly productive evening in terms of getting actual writing done, but interesting nonetheless...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1698645" width="1" height="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/Wacky+Ideas/default.aspx">Wacky Ideas</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_+4/default.aspx">C# 4</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category></item><item><title>Benchmarking: designing an API with unusual goals</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/02/02/benchmarking-designing-an-api-with-unusual-goals.aspx</link><pubDate>Mon, 02 Feb 2009 20:10:21 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1668242</guid><dc:creator>skeet</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1668242</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1668242</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/02/02/benchmarking-designing-an-api-with-unusual-goals.aspx#comments</comments><description>&lt;p&gt;In a couple of recent posts I&amp;#39;ve written about a &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2009/01/26/benchmarking-made-easy.aspx"&gt;benchmarking framework&lt;/a&gt; and the &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2009/01/29/for-vs-foreach-on-arrays-and-lists.aspx"&gt;results it produced for using for vs foreach in loops&lt;/a&gt;. I&amp;#39;m pleased with what I&amp;#39;ve done so far, but I don&amp;#39;t think I&amp;#39;ve gone far enough yet. In particular, while it&amp;#39;s good at testing multiple algorithms against a single input, it&amp;#39;s not good at trying several different inputs to demonstrate the complexity vs input size. I wanted to rethink the design at three levels - what the framework would be capable of, how developers would use it, and then the fine-grained level of what the API would look like in terms of types, methods etc. These may all sound quite similar on the face of it, but this project is somewhat different to a lot of other coding I&amp;#39;ve done, mostly because I want to lower the barrier to entry as far as humanly possible.&lt;/p&gt;  &lt;p&gt;Before any of this is meaningful, however, I really needed an idea of the fundamental goal. Why was I writing yet another benchmarking framework anyway? While I normally cringe at mission statements because they&amp;#39;re so badly formulated and used, I figured this time it would be helpful.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Minibench makes it &lt;strong&gt;easy&lt;/strong&gt; for &lt;strong&gt;developers&lt;/strong&gt; to &lt;strong&gt;write&lt;/strong&gt; and &lt;strong&gt;share&lt;/strong&gt; tests to &lt;strong&gt;investigate&lt;/strong&gt; and &lt;strong&gt;measure&lt;/strong&gt; code &lt;strong&gt;performance&lt;/strong&gt;.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The words in bold (or for the semantically inclined, the strong words) are the real meat of it. It&amp;#39;s quite scary that even within a single sentence there are seven key points to address. Some are quite simple, others cause grief. Now let&amp;#39;s look at each of the areas of design in turn.&lt;/p&gt;  &lt;p&gt;Each element of the design should either clearly contribute to the mission statement or help in a non-functional way (e.g. make the project feasible in a reasonable timeframe, avoid legal issues etc). I&amp;#39;m aware that with the length of this post, it sounds like I&amp;#39;m engaging in &amp;quot;big upfront design&amp;quot; but I&amp;#39;d like to think that it&amp;#39;s at least informed by my recent attempt, and that the design criteria here are statements of intent rather than implementation commitments. (Aargh, buzzword bingo... please persevere!)&lt;/p&gt;  &lt;h3&gt;What can it do?&lt;/h3&gt;  &lt;p&gt;As we&amp;#39;ve already said, it&amp;#39;s got to be able to measure code performance. That&amp;#39;s a pretty vague definition, however, so I&amp;#39;m going to restrict it a bit - the design is as much about saying what &lt;em&gt;isn&amp;#39;t&lt;/em&gt; included as what &lt;em&gt;is&lt;/em&gt;.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Each test will take the form of a single piece of code which is executed many times by the framework. It will have an input and an expected output. (Operations with no natural output can return a constant; I&amp;#39;m not going to make any special allowance for them.) &lt;/li&gt;    &lt;li&gt;The framework should take the tedium out of testing. In particular I don&amp;#39;t want to have to run it several times to get a reasonable number of iterations. I &lt;em&gt;suspect&lt;/em&gt; it won&amp;#39;t be feasible to get the framework to guess appropriate inputs, but that would be lovely if possible. &lt;/li&gt;    &lt;li&gt;Only wall time is measured. There are loads of different metrics which &lt;em&gt;could&lt;/em&gt; be applied: CPU execution time, memory usage, IO usage, lock contention - all kinds of things. Wall time (i.e. actual time elapsed, as measured by a clock on the wall) is by far the simplest to understand and capture, and it&amp;#39;s the one most frequently cited in newsgroup and forum questions in my experience. &lt;/li&gt;    &lt;li&gt;The benchmark is uninstrumented. I&amp;#39;m not going to start rewriting your code dynamically. Frankly this is for reasons of laziness. A really professional benchmarking system might take your IL and wrap it in a timing loop within a single method, somehow enforcing that the result of each iteration is used. I don&amp;#39;t believe that&amp;#39;s worth my time and energy, as well as quite possibly being beyond my capabilities. &lt;/li&gt;    &lt;li&gt;As a result of the previous bullet, the piece of code to be run lots of times needs to be non-trivial. The reality is that it&amp;#39;ll end up being called as a delegate. This is pretty quick, but if you&amp;#39;re just testing &amp;quot;is adding two doubles faster or slower than adding two floats&amp;quot; then you&amp;#39;ll need to put a bit more work in (e.g. having a loop in your own code as well). &lt;/li&gt;    &lt;li&gt;As well as the use case of &amp;quot;which of these algorithms performs the best with this input?&amp;quot; I want to support &amp;quot;how does the performance vary as a function of the input?&amp;quot; This should support multiple algorithms at the same time as multiple inputs. &lt;/li&gt;    &lt;li&gt;The output should be flexible but easy to describe in code. For single-input tests simple text output is fine (although the exact figures to produce can be interesting); for multiple inputs against multiple tests a graph would often be ideal. If I don&amp;#39;t have the energy to write a graphing output I should at least support writing to CSV or TSV so that a spreadsheet or graphing tool can do the heavy lifting. &lt;/li&gt;    &lt;li&gt;The output should be &lt;em&gt;useful&lt;/em&gt; - it should make it easy to compare the performance of different algorithms and/or inputs. It&amp;#39;s clear from the previous post here that &lt;em&gt;just&lt;/em&gt; including the scaled score doesn&amp;#39;t give an obvious meaning. Some careful wording in the output, as well as labeled columns, may be required. This is emphatically &lt;em&gt;not&lt;/em&gt; a dig at anyone confused by the last post - any confusion was my own fault.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Okay, that doesn&amp;#39;t sound too unreasonable. The next area is much harder, in my view.&lt;/p&gt;  &lt;h3&gt;How does a developer use it?&lt;/h3&gt;  &lt;p&gt;Possibly the most important word in the mission statement is &lt;strong&gt;share&lt;/strong&gt;. The reason I started this project at all is that I was fed up with spending ages writing timing loops for benchmarks which I&amp;#39;d then post on newsgroups or Stack Overflow. That means there are two (overlapping) categories of user:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;A developer writing a test. This needs to be easy, but that&amp;#39;s an aspect of design that I&amp;#39;m reasonably familiar with. I&amp;#39;m not saying I&amp;#39;m &lt;em&gt;good&lt;/em&gt; at it, but at least I have some prior experience. &lt;/li&gt;    &lt;li&gt;A developer reading a newsgroup/forum post, and wanting to run the benchark for themselves. This distribution aspect is the hard bit - or at least the bit requiring imagination. I want the barrier to running the code to be really, &lt;em&gt;really&lt;/em&gt; low. I suspect that there&amp;#39;ll be a &amp;quot;fear of the unknown&amp;quot; to start with which is hard to conquer, but if the framework becomes widely used I want the reader&amp;#39;s reaction to be: &amp;quot;Ah, there&amp;#39;s a MiniBench for this. I&amp;#39;m confident that I can download and run this code with almost no effort.&amp;quot; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;This second bullet is the one that my friend Douglas and I have been discussing over the weekend, in some ways playing a game of one-upmanship: &amp;quot;I can think of an idea which is &lt;em&gt;even easier&lt;/em&gt; than yours.&amp;quot; It&amp;#39;s a really fun game to play. Things we&amp;#39;ve thought about so far:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;A web page which lets you upload a full program (without the framework) and spits out a URL which can be posted onto Stack Overflow etc. The user would then choose from the following formats: &lt;/li&gt;    &lt;ul&gt;     &lt;li&gt;Single .cs file containing the whole program - just compile and run. (This would also be shown on the download page.) &lt;/li&gt;      &lt;li&gt;Test code only - for those whole already have the framework &lt;/li&gt;      &lt;li&gt;Batch file - just run it to extract/build/run the C# code. &lt;/li&gt;      &lt;li&gt;NAnt project file containing the C# code embedded in it - just run NAnt &lt;/li&gt;      &lt;li&gt;MSBuild project file - ditto but with msbuild. &lt;/li&gt;      &lt;li&gt;Zipped project – open the project to load the test in one file and the framework code in other (possibly separate) .cs files &lt;/li&gt;      &lt;li&gt;Zipped solution – open to load two projects: the test code in one and the framework in the other &lt;/li&gt;   &lt;/ul&gt;    &lt;li&gt;A web page which which lets you upload your results and browse the results of others &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Nothing&amp;#39;s finalised here, but I like the general idea. I&amp;#39;ve managed (fairly easily) to write a &amp;quot;self-building&amp;quot; batch file, but I haven&amp;#39;t tried with NAnt/MSBuild yet. I can&amp;#39;t imagine it&amp;#39;s that hard - but then I&amp;#39;m not sure how much value there is either. What I &lt;em&gt;do&lt;/em&gt; want to try to aim for is users running the tests properly, first time, without much effort. Again, looking back at the last post, I want to make it obvious to users if they&amp;#39;re running under a debugger, which is almost always the wrong thing to be doing. (I&amp;#39;m pretty sure there&amp;#39;s an API for this somewhere, and if there&amp;#39;s not I&amp;#39;m sure I can work out an evil way of detecting it anyway.)&lt;/p&gt;  &lt;p&gt;The main thing is the ease of downloading and running the benchmark. I can&amp;#39;t see how it could be much easier than &amp;quot;follow link; choose format and download; run batch file&amp;quot; - unless the link itself was to the batch file, of course. (That would make it harder to use for people who wanted to get the source in a more normal format, of course.)&lt;/p&gt;  &lt;p&gt;Going back to the point of view of the developer writing the test, I need to make sure it&amp;#39;s easy enough for &lt;em&gt;me&lt;/em&gt; to use from home, work and on the train. That &lt;em&gt;may&lt;/em&gt; mean a web page where I can just type in code, the input and expected output, and let it fill in the rest of the code for me. It &lt;em&gt;may&lt;/em&gt; mean compiling a source file against a library from the command line. It &lt;em&gt;may&lt;/em&gt; mean compiling a source file against the source code of the framework from the command line, with the framework code all in one file. It &lt;em&gt;may&lt;/em&gt; mean building in Visual Studio. I&amp;#39;d like to make all of these cases as simple as possible - which is likely to make it simple for other developers as well. I&amp;#39;m not planning on optimising the experience when it comes to writing a benchmark on my mobile though - that might be a step too far!&lt;/p&gt;  &lt;h3&gt;What should the API look like?&lt;/h3&gt;  &lt;p&gt;When we get down to the nitty-gritty of types and methods, I think what I&amp;#39;ve got is a good starting point. There are still a few things to think about though:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;We &lt;em&gt;nearly&lt;/em&gt; have the functionality required for running a suite with different inputs already - the only problem is that we&amp;#39;re specifying the input (and expected output) in the constructor rather than as parameters to the RunTests method. I could change that... but then we lose the benefit of type inference when creating the suite. I haven&amp;#39;t resolved this to my satisfaction yet :(&lt;/li&gt;    &lt;li&gt;The idea of having the suite automatically set up using attributed methods appeals, although we&amp;#39;d still need a Main method to create the suite and format the output. The suite creation can be simplified, but the chances of magically picking the most appropriate output are fairly slim. I suppose it could go for the &amp;quot;scale to best by number of iterations and show all columns&amp;quot; option by default... that still leaves the input and expected output, of course. I&amp;#39;m sure I&amp;#39;ll have &lt;em&gt;something&lt;/em&gt; like this as an option, but I don&amp;#39;t know how far it will go.&lt;/li&gt;    &lt;li&gt;The &amp;quot;configuration&amp;quot; side of it is expressed as a couple of constants at the moment. These control the minimum amount of time to run tests for before we believe we&amp;#39;ll be able to guess how many iterations we&amp;#39;ll need to get close to the target time, and the target time itself. These are currently set at 2 seconds and 30 seconds respectively - but when running tests just to check that you&amp;#39;ve got the right output format etc, that&amp;#39;s far too long. I suspect I should make a test suite have a configuration, and &lt;em&gt;default&lt;/em&gt; to those constants but allow them to be specified on the command line as well, or explicitly in code.&lt;/li&gt;    &lt;li&gt;Why do we need to set the expected output? In many cases you can be pretty confident that at least &lt;em&gt;one&lt;/em&gt; of the test cases will be correct - so it&amp;#39;s probably simpler just to run each test once and check that the results are the same for all of them, and take that as the expected output. If you don&amp;#39;t have to specify the expected output, it becomes easier to specify a sequence of inputs to test.&lt;/li&gt;    &lt;li&gt;Currently BenchmarkResult is nongeneric. This makes things simpler internally - but should a result know the input that it was derived from? Or should the ResultSuite (which is also nongeneric) know the input that has been applied to all its functions? The information will certainly need to be &lt;em&gt;somewhere&lt;/em&gt; so that it can be output appropriately in the multiple input case.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;My main points of design focus around three areas:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Is it easy to pick up? The more flexible it is, with lots of options, the more daunting it may seem.&lt;/li&gt;    &lt;li&gt;Is it flexible enough to be useful in a variety of situations? I don&amp;#39;t know what users will want to benchmark - and I don&amp;#39;t build the right tool, it will be worthless to them.&lt;/li&gt;    &lt;li&gt;Is the resulting test code easy and brief enough to include in a forum post, with a link to the full program? Will readers understand it?&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;As you can see, these are aimed at three slightly different people: the first time test writer, the veteran test writer, and the first time test reader. Getting the balance between the three is tricky.&lt;/p&gt;  &lt;h3&gt;What&amp;#39;s next?&lt;/h3&gt;  &lt;p&gt;I haven&amp;#39;t started rewriting the framework yet, but will probably do so soon. This time I hope to do it in a rather more test-driven way, although of course the timing-specific elements will be tricky unless I start using a programmatic clock etc. I&amp;#39;d really like comments around this whole process:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Is this worth doing?&lt;/li&gt;    &lt;li&gt;Am I asking the right questions?&lt;/li&gt;    &lt;li&gt;Are my answers so far headed in the right direction?&lt;/li&gt;    &lt;li&gt;What else haven&amp;#39;t I thought of?&lt;/li&gt; &lt;/ul&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1668242" width="1" height="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><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Benchmarking/default.aspx">Benchmarking</category></item><item><title>Quick rant: why isn't there an Exception(string, params object[]) constructor?</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/01/23/quick-rant-why-isn-t-there-an-exception-string-params-object-constructor.aspx</link><pubDate>Fri, 23 Jan 2009 21:42:52 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1665160</guid><dc:creator>skeet</dc:creator><slash:comments>26</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1665160</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1665160</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/01/23/quick-rant-why-isn-t-there-an-exception-string-params-object-constructor.aspx#comments</comments><description>&lt;p&gt;This &lt;a href="http://stackoverflow.com/questions/474564"&gt;Stack Overflow question&lt;/a&gt; has reminded me of something I often wish existed in common exception constructors - an overload taking a format string and values. For instance, it would be really nice to be able to write:&lt;/p&gt; &lt;div class="code"&gt;&lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt; IOException(&lt;span class="String"&gt;&amp;quot;Expected to read {0} bytes but only {1} were available&amp;quot;&lt;/span&gt;,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; requiredSize, bytesRead); &lt;/div&gt; &lt;p&gt;Of course, with no way of explicitly inheriting constructors (which I almost always want for exceptions, and almost never want for anything else) it would mean yet another overload to copy and paste from another exception, but the times when I&amp;#39;ve actually written it in my own exceptions it&amp;#39;s been &lt;em&gt;hugely&lt;/em&gt; handy, particularly for tricky cases where you&amp;#39;ve got a lot of data to include in the message. (You&amp;#39;d also want an overload taking a nested exception first as well, adding to the baggage...)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1665160" width="1" height="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><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/Stack+Overflow/default.aspx">Stack Overflow</category></item></channel></rss>