<?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 : Evil Code, C#</title><link>http://msmvps.com/blogs/jon_skeet/archive/tags/Evil+Code/C_2300_/default.aspx</link><description>Tags: Evil Code, C#</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><item><title>More fun with DateTime</title><link>http://msmvps.com/blogs/jon_skeet/archive/2012/05/02/more-fun-with-datetime.aspx</link><pubDate>Wed, 02 May 2012 20:12:43 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1809416</guid><dc:creator>skeet</dc:creator><slash:comments>19</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1809416</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1809416</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/05/02/more-fun-with-datetime.aspx#comments</comments><description>&lt;p&gt;(Note that this is deliberately not posted in the &lt;a href="http://noda-time.blogspot.com/"&gt;Noda Time blog&lt;/a&gt;. I reckon it&amp;#39;s of wider interest from a design perspective, and I won&amp;#39;t be posting any of the equivalent &lt;a href="http://noda-time.googlecode.com"&gt;Noda Time&lt;/a&gt; code. I&amp;#39;ll just say now that we don&amp;#39;t have this sort of craziness in Noda Time, and leave it at that...)&lt;/p&gt;  &lt;p&gt;A few weeks ago, I was answering a Stack Overflow question when I noticed an operation around dates and times which &lt;em&gt;should&lt;/em&gt; have been losing information apparently not doing so. I investigated further, and discovered some &amp;quot;interesting&amp;quot; aspects of both DateTime and TimeZoneInfo. In an effort to keep this post down to a readable length (at least for most readers; certain WebDriver developers who shall remain nameless have probably given up by now already) I&amp;#39;ll save the TimeZoneInfo bits for another post.&lt;/p&gt;  &lt;h2&gt;Background: daylight saving transitions and ambiguous times&lt;/h2&gt;  &lt;p&gt;There&amp;#39;s one piece of &lt;em&gt;inherent&lt;/em&gt; date/time complexity you&amp;#39;ll need to understand for this post to make sense: sometimes, a local date/time occurs twice. For the purposes of this post, I&amp;#39;m going to assume you&amp;#39;re in the UK time zone. On October 28th 2012, at 2am local time (1am UTC), UK clocks will go back to 1am local time. So 1:20am local time occurs twice - once at 12:20am UTC (in daylight saving time, BST), and once at 1:20am UTC (in standard time, GMT).&lt;/p&gt;  &lt;p&gt;If you want to run any of the code in this post and you&amp;#39;re &lt;em&gt;not&lt;/em&gt; in the UK, please adjust the dates and times used to a similar ambiguity for when your clocks go back. If you happen to be in a time zone which doesn&amp;#39;t observe daylight savings, I&amp;#39;m afraid you&amp;#39;ll have to adjust your system time zone in order to see the effect for yourself.&lt;/p&gt;  &lt;h2&gt;DateTime.Kind and conversions&lt;/h2&gt;  &lt;p&gt;As you may already know, as of .NET 2.0, DateTime has a &lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.kind.aspx"&gt;Kind&lt;/a&gt; property, of type &lt;a href="http://msdn.microsoft.com/en-us/library/shx7s921.aspx"&gt;DateTimeKind&lt;/a&gt; - an enum with the following values:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Local: The DateTime is considered to be in the &lt;em&gt;system time zone&lt;/em&gt;. Not an arbitrary &amp;quot;local time in some time zone&amp;quot;, but in the specific current system time zone. &lt;/li&gt;    &lt;li&gt;Utc: The DateTime is considered to be in UTC (corollary: it always unambiguously represents an instant in time) &lt;/li&gt;    &lt;li&gt;Unspecified: This means different things in different contexts, but it&amp;#39;s a sort of &amp;quot;don&amp;#39;t know&amp;quot; kind; this is closer to &amp;quot;local time in some time zone&amp;quot; which is represented as LocalDateTime in Noda Time. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;DateTime provides three methods to convert between the kinds:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx"&gt;ToUniversalTime&lt;/a&gt;: if the original kind is Local or Unspecified, convert it from local time to universal time in the system time zone. If the original kind is Utc, this is a no-op. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx"&gt;ToLocalTime&lt;/a&gt;: if the original kind is Utc or Unspecified, convert it from UTC to local time. If the original kind is Local, this is a no-op. &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.specifykind.aspx"&gt;SpecifyKind&lt;/a&gt;: keep the existing date/time, but &lt;em&gt;just&lt;/em&gt; change the kind. (So 7am stays as 7am, but it changes the &lt;em&gt;meaning&lt;/em&gt; of that 7am effectively.) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;(Prior to .NET 2.0, ToUniversalTime and ToLocalTime were already present, but always &lt;em&gt;assumed&lt;/em&gt; the original value needed conversion - so if you called x.ToLocalTime().ToLocalTime().ToLocalTime() the result would probably end up with the appropriate offset from UTC being applied three times!)&lt;/p&gt;  &lt;p&gt;Of course, none of these methods change the existing value - DateTime is immutable, and a value type - instead, they return a &lt;em&gt;new&lt;/em&gt; value.&lt;/p&gt;  &lt;h2&gt;DateTime&amp;#39;s Deep Dark Secret&lt;/h2&gt;  &lt;p&gt;(The code in this section is presented in several chunks, but it forms a single complete piece of code - later chunks refer to variables in earlier chunks. Put it all together in a Main method to run it.)&lt;/p&gt;  &lt;p&gt;Armed with the information in the previous sections, we should be able to make DateTime lose data. If we start with 12:20am UTC and 1:20am UTC on October 28th as DateTimes with a kind of Utc, when we convert them to local time (on a system in the UK time zone) we should get 1:20am in both cases due to the daylight saving transition. Indeed, that works:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Start with different UTC values around a DST transition&lt;/span&gt;     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; original1 = &lt;span class="Keyword"&gt;new&lt;/span&gt; DateTime(2012, 10, 28, 0, 20, 0, DateTimeKind.Utc);     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; original2 = &lt;span class="Keyword"&gt;new&lt;/span&gt; DateTime(2012, 10, 28, 1, 20, 0, DateTimeKind.Utc);     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Convert to local time&lt;/span&gt;     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local1 = original1.ToLocalTime();     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local2 = original2.ToLocalTime();     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Result is the same for both values. Information loss?&lt;/span&gt;     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; expected = &lt;span class="Keyword"&gt;new&lt;/span&gt; DateTime(2012, 10, 28, 1, 20, 0, DateTimeKind.Local);     &lt;br /&gt;Console.WriteLine(local1 == expected); &lt;span class="InlineComment"&gt;// True&lt;/span&gt;     &lt;br /&gt;Console.WriteLine(local2 == expected); &lt;span class="InlineComment"&gt;// True&lt;/span&gt;     &lt;br /&gt;Console.WriteLine(local1 == local2);&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// True&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;If we&amp;#39;ve started with two &lt;em&gt;different&lt;/em&gt; values, applied the same operation to both, and ended up with equal values, then we must have lost information, right? That doesn&amp;#39;t mean that operation is &amp;quot;bad&amp;quot; any more than &amp;quot;dividing by 2&amp;quot; is bad. You ought to be aware of that information loss, that&amp;#39;s all.&lt;/p&gt;  &lt;p&gt;So, we ought to be able to demonstrate that information loss further by converting back from local time to universal time. Here we have the opposite problem: from our local time of 1:20am, we have &lt;em&gt;two&lt;/em&gt; valid universal times we could convert to - either 12:20am UTC or 1:20am UTC. Both answers would be correct - they are universal times at which the local time would be 1:20am. So which one will get picked? Well... here&amp;#39;s the surprising bit:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Convert back to UTC &lt;/span&gt;    &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; roundTrip1 = local1.ToUniversalTime();&amp;#160; &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; roundTrip2 = local2.ToUniversalTime();     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Values round-trip correctly! Information has been recovered... &lt;/span&gt;    &lt;br /&gt;Console.WriteLine(roundTrip1 == original1);&amp;#160; &lt;span class="InlineComment"&gt;// True &lt;/span&gt;    &lt;br /&gt;Console.WriteLine(roundTrip2 == original2);&amp;#160; &lt;span class="InlineComment"&gt;// True &lt;/span&gt;    &lt;br /&gt;Console.WriteLine(roundTrip1 == roundTrip2); &lt;span class="InlineComment"&gt;// False&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;Somehow, each of the local values &lt;em&gt;knows&lt;/em&gt; which universal value it came from. The The information has been recovered, so the reverse conversion round-trips each value back to its original one. How is that possible?&lt;/p&gt;  &lt;p&gt;It turns out that DateTime actually has &lt;em&gt;four&lt;/em&gt; potential kinds: Local, Utc, Unspecified, and &amp;quot;local but treat it as the earlier option when resolving ambiguity&amp;quot;. A DateTime is really just a 64-bit number of ticks, but because the range of DateTime is only January 1st 0001 to December 31st 9999. That range can be represented in 62 bits, leaving 2 bits &amp;quot;spare&amp;quot; to represent the kind. 2 bits gives 4 possible values... the three documented ones and the shadowy extra one.&lt;/p&gt;  &lt;p&gt;Through experimentation, I&amp;#39;ve discovered that the kind is preserved if you perform arithmetic on the value, too... so if you go to another &amp;quot;fall back&amp;quot; DST transition such as October 30th 2011, the ambiguity resolution works the same way as before:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local3 = local1.AddYears(-1).AddDays(2);&amp;#160; &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local4 = local2.AddYears(-1).AddDays(2);&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;Console.WriteLine(local3.ToUniversalTime().Hour); &lt;span class="InlineComment"&gt;// 0 &lt;/span&gt;    &lt;br /&gt;Console.WriteLine(local4.ToUniversalTime().Hour); &lt;span class="InlineComment"&gt;// 1&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;If you use DateTime.SpecifyKind with DateTimeKind.Local, however, it goes back to the &amp;quot;normal&amp;quot; kind, even though it &lt;em&gt;looks&lt;/em&gt; like it should be a no-op:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Should be a no-op? &lt;/span&gt;    &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; local5 = DateTime.SpecifyKind(local1, local1.Kind);&amp;#160; &lt;br /&gt;Console.WriteLine(local5.ToUniversalTime().Hour); &lt;span class="InlineComment"&gt;// 1&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;Is this correct behaviour? Or should it be a no-op, just like calling ToLocalTime on a &amp;quot;local&amp;quot; DateTime is? (Yes, I&amp;#39;ve checked - that doesn&amp;#39;t lose the information.) It&amp;#39;s hard to say, really, as this whole business appears to be undocumented... at least, I haven&amp;#39;t seen anything in MSDN about it. (Please add a link in the comments if you find something. The behaviour actually goes against what&amp;#39;s documented, as far as I can tell.)&lt;/p&gt;  &lt;p&gt;I haven&amp;#39;t looked into whether various forms of serialization preserve values like this faithfully, by the way - but you&amp;#39;d have to work hard to reproduce it in non-framework code. You can&amp;#39;t explicitly construct a DateTime with the &amp;quot;extra&amp;quot; kind; the only ways I know of to create such a value are via a conversion to local time or through arithmetic on a value which already has the kind. (Admittedly if you&amp;#39;re serializing a DateTime with a Kind of Local, you&amp;#39;re already on potentially shaky ground, given that you could be deserializing it on a machine with a different system time zone.)&lt;/p&gt;  &lt;h2&gt;Unkind comparisons&lt;/h2&gt;  &lt;p&gt;I&amp;#39;ve misled you a little, I have to admit. In the code above, when I compared the &amp;quot;expected&amp;quot; value with the results of the first conversions, I deliberately specified DateTimeKind.Local in the constructor call. After all, that&amp;#39;s the kind we &lt;em&gt;do&lt;/em&gt; expect. Well, yes - but I then printed the result of comparing this value with local1 and local2... and those comparisons would have been the same regardless of the kind I&amp;#39;d specified in the constructor.&lt;/p&gt;  &lt;p&gt;All comparisons between DateTimes ignore the Kind property. It&amp;#39;s not just restricted to equality. So for example, consider this comparison:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// In June: Local time is UTC+1, so 8am UTC is 9am local &lt;/span&gt;    &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; dt1 = &lt;span class="Keyword"&gt;new&lt;/span&gt; DateTime(2012, 6, 1, 8, 0, 0, DateTimeKind.Utc);&amp;#160; &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; dt2 = &lt;span class="Keyword"&gt;new&lt;/span&gt; DateTime(2012, 6, 1, 8, 30, 0, DateTimeKind.Local);&amp;#160; &lt;br /&gt;Console.WriteLine(dt1 &amp;lt; dt2); &lt;span class="InlineComment"&gt;// True&lt;/span&gt; &lt;/div&gt;  &lt;p&gt;When viewed in terms of &amp;quot;what instants in time do these both represent?&amp;quot; the answer here is wrong - when you convert both values into the same time zone (in either direction), dt1 occurs &lt;em&gt;after&lt;/em&gt; dt2. But a simple look at the properties tells a different story. In practice, I suspect that most comparisons between DateTime values of different kinds involve code which is at best sloppy and is quite possibly broken in a meaningful way.&lt;/p&gt;  &lt;p&gt;Of course, if you bring Kind=Unspecified into the picture, it becomes impossible to compare meaningfully in a kind-sensitive way. Is 12am UTC before or after 1am Unspecified? It depends what time zone you later use.&lt;/p&gt;  &lt;p&gt;To be clear, it &lt;em&gt;is&lt;/em&gt; a hard-to-resolve issue, and one that we don&amp;#39;t do terribly well at in Noda Time at the moment for ZonedDateTime. (And even with just LocalDateTime you&amp;#39;ve got issues between calendars.) This is a situation where providing separate Comparer&amp;lt;T&amp;gt; implementations works nicely - so you can explicitly say what kind of comparison you want.&lt;/p&gt;  &lt;h2&gt;Conclusions&lt;/h2&gt;  &lt;p&gt;There&amp;#39;s more fun to be had with a similar situation when we look at TimeZoneInfo, but for now, a few lessons:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Giving a type different &amp;quot;modes&amp;quot; which make it mean fairly significantly different things is likely to cause headaches &lt;/li&gt;    &lt;li&gt;Keeping one of those modes secret (and preventing users from even constructing a value in that mode directly) leads to even more fun and games &lt;/li&gt;    &lt;li&gt;If two instances of your type are considered &amp;quot;equal&amp;quot; but behave differently, you should at least consider whether there&amp;#39;s something smelly going on &lt;/li&gt;    &lt;li&gt;There&amp;#39;s &lt;em&gt;always&lt;/em&gt; more fun to be had with DateTime... &lt;/li&gt; &lt;/ul&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1809416" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Evil+Code/default.aspx">Evil Code</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Noda+Time/default.aspx">Noda Time</category></item><item><title>Type initializer circular dependencies</title><link>http://msmvps.com/blogs/jon_skeet/archive/2012/04/07/type-initializer-circular-dependencies.aspx</link><pubDate>Sat, 07 Apr 2012 09:35:45 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1808561</guid><dc:creator>skeet</dc:creator><slash:comments>25</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1808561</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1808561</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2012/04/07/type-initializer-circular-dependencies.aspx#comments</comments><description>&lt;p&gt;To some readers, the title of this post may induce nightmarish recollections of late-night debugging sessions. To others it may be simply the epitome of jargon. Just to break the jargon down a bit:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Type initializer: the code executed to initialize the static variables of a class, and the static constructor &lt;/li&gt;    &lt;li&gt;Circular dependency: two bits of code which depend on each other - in this case, two classes whose type initializers each require that the other class is initialized &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;A quick example of the kind of problem I&amp;#39;m talking about would be helpful here. What would you expect this code to print?&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Test     &lt;br /&gt;{&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(First.Beta);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; First     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; Alpha = 5;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; Beta = Second.Gamma;     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Second     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; Gamma = First.Alpha;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Of course, without even glancing at the specification, any expectations are pretty irrelevant. Here&amp;#39;s what the spec (section 10.5.5.1 of the C# 4 version):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class. &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In addition to the language specification, the CLI specification gives more details about type initialization in the face of circular dependencies and multiple threads. I won&amp;#39;t post the details here, but the gist of it is:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Type initialization acts like a lock, to prevent more than one thread from initializing a type &lt;/li&gt;    &lt;li&gt;If the CLI notices that type A needs to be initialized in order to make progress, but it&amp;#39;s &lt;em&gt;already in the process&lt;/em&gt; of initializing type A &lt;em&gt;in the same thread&lt;/em&gt;, it continues as if the type were already initialized. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So here&amp;#39;s what you &lt;em&gt;might&lt;/em&gt; expect to happen:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Initialize Test: no further action required &lt;/li&gt;    &lt;li&gt;Start running Main &lt;/li&gt;    &lt;li&gt;Start initializing First (as we need First.Beta) &lt;/li&gt;    &lt;li&gt;Set First.Alpha to 5 &lt;/li&gt;    &lt;li&gt;Start initializing Second (as we need Second.Gamma) &lt;/li&gt;    &lt;li&gt;Set Second.Gamma to First.Alpha (5) &lt;/li&gt;    &lt;li&gt;End initializing Second &lt;/li&gt;    &lt;li&gt;Set First.Beta to Second.Gamma (5) &lt;/li&gt;    &lt;li&gt;End initializing First &lt;/li&gt;    &lt;li&gt;Print 5 &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Here&amp;#39;s what &lt;em&gt;actually&lt;/em&gt; happens - on my box, running .NET 4.5 beta. (I know that &lt;a href="https://msmvps.com/blogs/jon_skeet/archive/2010/01/26/type-initialization-changes-in-net-4-0.aspx"&gt;type initialization changed for .NET 4&lt;/a&gt;, for example. I don&amp;#39;t &lt;em&gt;know&lt;/em&gt; of any changes for .NET 4.5, but I&amp;#39;m not going to claim it&amp;#39;s impossible.)&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Initialize Test: no further action required &lt;/li&gt;    &lt;li&gt;Start running Main &lt;/li&gt;    &lt;li&gt;Start initializing First (as we need First.Beta) &lt;/li&gt;    &lt;li&gt;Start initializing Second (we &lt;em&gt;will&lt;/em&gt; need Second.Gamma) &lt;/li&gt;    &lt;li&gt;Set Second.Gamma to First.Alpha (0) &lt;/li&gt;    &lt;li&gt;End initializing Second &lt;/li&gt;    &lt;li&gt;Set First.Alpha to 5 &lt;/li&gt;    &lt;li&gt;Set First.Beta to Second.Gamma (0) &lt;/li&gt;    &lt;li&gt;End initializing First &lt;/li&gt;    &lt;li&gt;Print 0 &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Step 5 is the interesting one here. We know that we need First to be initialized, in order to get First.Alpha, but this thread is &lt;em&gt;already&lt;/em&gt; initializing First (we started in step 3) so we just access First.Alpha and hope that it&amp;#39;s got the right value. As it happens, that variable initializer hasn&amp;#39;t been executed yet. Oops.&lt;/p&gt;  &lt;p&gt;(One subtlety here is that I &lt;em&gt;could &lt;/em&gt;have declared all these variables as constants instead using &amp;quot;const&amp;quot; which would have avoided all these problems.)&lt;/p&gt;  &lt;h1&gt;Back in the real world...&lt;/h1&gt;  &lt;p&gt;Hopefully that example makes it clear why circular dependencies in type initializers are nasty. They&amp;#39;re hard to spot, hard to debug, and hard to test. Pretty much your classic &lt;a href="http://en.wikipedia.org/wiki/Heisenbug"&gt;Heisenbug&lt;/a&gt;, really. It&amp;#39;s important to note that if the program above had &lt;em&gt;happened&lt;/em&gt; to initialize Second first (to access a different variable, for example) we could have ended up with a different result. In particular, it&amp;#39;s easy to get into a situation where running &lt;em&gt;all&lt;/em&gt; your unit tests can cause a failure - but if you run &lt;em&gt;just&lt;/em&gt; the failing test, it passes.&lt;/p&gt;  &lt;p&gt;One way of avoiding all of this is never to use any type initializers for anything, of course. In many cases that&amp;#39;s exactly the right solution - but often there &lt;em&gt;are&lt;/em&gt; natural uses, particularly for well-known values such as &lt;a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.utf8.aspx"&gt;Encoding.Utf8&lt;/a&gt;, &lt;a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.utc.aspx"&gt;TimeZoneInfo.Utc&lt;/a&gt; and the like. Note that in both of those cases they are static &lt;em&gt;properties&lt;/em&gt;, but I would expect them to be backed by static fields. I&amp;#39;m somewhat ambivalent between using public static readonly fields and public static get-only properties - but as we&amp;#39;ll see later, there&amp;#39;s a definite advantage to using properties.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://noda-time.googlecode.com"&gt;Noda Time&lt;/a&gt; has quite a few values like this - partly because so many of its types are immutable. It makes sense to create a single UTC time zone, a single ISO calendar system, a single &amp;quot;pattern&amp;quot; (text formatter/parser) for each of a variety of common cases. In addition to the publicly visible values, there are various static variables used internally, mostly for caching purposes. All of this definitely adds complexity - &lt;em&gt;and&lt;/em&gt; makes it harder to test - but the performance benefits can be significant.&lt;/p&gt;  &lt;p&gt;Unfortunately, a lot of these values end up with fairly natural circular dependencies - as I discovered just recently, where adding a new static field caused all kinds of breakage. I was able to fix the immediate cause, but it left me concerned about the integrity of the code. I&amp;#39;d fixed the one failure I knew about - but what about any others?&lt;/p&gt;  &lt;h1&gt;Testing type initialization&lt;/h1&gt;  &lt;p&gt;One of the biggest issues with type initialization is the order-sensitivity - combined with the way that once a type has been initialized once, that&amp;#39;s it for that AppDomain. As I showed earlier, it&amp;#39;s possible that initializing types in one particular order causes a problem, but a different order won&amp;#39;t.&lt;/p&gt;  &lt;p&gt;I&amp;#39;ve decided that for Noda Time at least, I want to be reasonably sure that type initialization circularity isn&amp;#39;t going to bite me. So I want to validate that no type initializers form cycles, whatever order the types are initialized in. Logically if we can detect a cycle starting with one type, we &lt;em&gt;ought&lt;/em&gt; to be able to detect it starting with any of the other types in that cycle - but I&amp;#39;m sufficiently concerned about weird corner cases that I&amp;#39;d rather just take a brute force approach.&lt;/p&gt;  &lt;p&gt;So, as a rough plan:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Start with an empty set of dependencies &lt;/li&gt;    &lt;li&gt;For each type in the target assembly:      &lt;ul&gt;       &lt;li&gt;Create a new AppDomain &lt;/li&gt;        &lt;li&gt;Load the target assembly into it &lt;/li&gt;        &lt;li&gt;Force the type to be initialized &lt;/li&gt;        &lt;li&gt;Take a stack trace at the start of each type initializer and record any dependencies &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;Look for cycles in the complete set of dependencies &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Note that we&amp;#39;ll never spot a cycle within any single AppDomain, due to the way that type initialization works. We have to put together the results for multiple initialization sequences to try to find a cycle.&lt;/p&gt;  &lt;p&gt;A description of the code would probably be harder to follow than the code itself, but the code is relatively long - I&amp;#39;ve included it at the end of this post to avoid intefering with the narrative flow. For more up-to-date versions in the future, look at the &lt;a href="http://code.google.com/p/noda-time/source/browse/"&gt;Noda Time repository&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;This &lt;em&gt;isn&amp;#39;t&lt;/em&gt; a terribly nice solution, for various reasons:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Creating a new AppDomain and loading assemblies into it &lt;em&gt;from a unit test runner&lt;/em&gt; isn&amp;#39;t as simple as it might be. My code doesn&amp;#39;t currently work with NCrunch; I don&amp;#39;t know how it finds its assemblies yet. When I&amp;#39;ve fixed that, I&amp;#39;m sure other test runners would still be broken. Likewise I&amp;#39;ve had to explicitly filter types to get TeamCity (the continuous integration system Noda Time uses) to work properly. Currently, you&amp;#39;d need to edit the test code to change the filters. (It&amp;#39;s possible that there are better ways of filtering, of course.) &lt;/li&gt;    &lt;li&gt;It relies on each type within the production code which has an &amp;quot;interesting&amp;quot; type initializer to have a line like this:      &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; TypeInitializationChecking = NodaTime.Utility.TypeInitializationChecker.RecordInitializationStart(); &lt;/div&gt;   &lt;/li&gt;    &lt;li&gt;Not only does the previous line need to be added to the production code - it clearly gets executed each time, and takes up heap space per type. It&amp;#39;s only 4 bytes for each type involved, and it does no real work when we&amp;#39;re not testing, but it&amp;#39;s a nuisance anyway. I &lt;em&gt;could&lt;/em&gt; use preprocessor directives to remove the code from non-debug or non-test-targeted builds, but that would look even messier. &lt;/li&gt;    &lt;li&gt;It only picks up cycles which occur when running the version of .NET the tests happen to execute on. Given that there are ordering changes for different versions, I wouldn&amp;#39;t like to claim this is 100% bullet-proof. Likewise if there are only cycles when you&amp;#39;re running in some specific cultures (or other environmental features), it won&amp;#39;t necessarily pick those up. &lt;/li&gt;    &lt;li&gt;I&amp;#39;ve deliberately not tried to make the testing code thread-safe. That&amp;#39;s fine in Noda Time - I don&amp;#39;t have any asynchronous operations or new threads in Noda Time at all - but other code may need to make this more robust. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So with all these caveats, is it still worth it? Absolutely: &lt;strong&gt;it&amp;#39;s already found bugs which have now been fixed&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;In fact, the test didn&amp;#39;t get as far as reporting cycles to start with - it turned out that if you initialized one particular type first, the type initializer would fail with a NullReferenceException. Ouch! Once I&amp;#39;d fixed that, there were still quite a few problems to fix. Somewhat coincidentally, fixing them improved the design too - although the user-visible API didn&amp;#39;t change at all.&lt;/p&gt;  &lt;h1&gt;Fixing type initializer cycles&lt;/h1&gt;  &lt;p&gt;In the past, I&amp;#39;ve occasionally &amp;quot;fixed&amp;quot; type initialization ordering problems by simply moving fields around. The cycles still existed, but I figured out how to make them harmless. I can say now that &lt;em&gt;this approach does not scale, and is more effort than it&amp;#39;s worth&lt;/em&gt;. The code ends up being brittle, hard to think about, and once you&amp;#39;ve got more than a couple of types involved it&amp;#39;s really error-prone, at least for my brain. It&amp;#39;s much better to break the cycle completely. To this end, I&amp;#39;ve ended up using a fairly simple technique to defer initialization of static variables. It&amp;#39;s a poor-man&amp;#39;s &lt;a href="http://msdn.microsoft.com/en-us/library/dd642331.aspx"&gt;Lazy&amp;lt;T&amp;gt;&lt;/a&gt;, to some extent - but I&amp;#39;d rather not have to write Lazy&amp;lt;T&amp;gt; myself, and we&amp;#39;re currently targeting .NET 3.5...&lt;/p&gt;  &lt;p&gt;Basically, instead of exposing a public static readonly field which creates the cycle, you expose a public static readonly property - which returns an internal static readonly field &lt;em&gt;in a nested, private static class&lt;/em&gt;. We still get the nice thread-safe once-only initialization of a type initializer, but the nested type won&amp;#39;t be initialized until it needs to be. (In theory it &lt;em&gt;could&lt;/em&gt; be initialized earlier, but a static constructor would ensure it isn&amp;#39;t.) So long as nothing within the &lt;em&gt;rest&lt;/em&gt; of the type initializer for the containing class uses that property, we avoid the cycle.&lt;/p&gt;  &lt;p&gt;So instead of this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Requires Bar to be initialized - if Bar also requires Foo to be&lt;/span&gt;     &lt;br /&gt;&lt;span class="InlineComment"&gt;// initialized, we have a problem...&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; Foo SimpleFoo = &lt;span class="Keyword"&gt;new&lt;/span&gt; Foo(Bar.Zero); &lt;/div&gt;  &lt;p&gt;We might have:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; Foo SimpleFoo { get { &lt;span class="Statement"&gt;return&lt;/span&gt; Constants.SimpleFoo; } }     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Constants     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; TypeInitializationChecking = NodaTime.Utility.TypeInitializationChecker.RecordInitializationStart();&amp;#160; &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// This requires both Foo and Bar to be initialized, but that&amp;#39;s okay&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// so long as neither of them require Foo.Constants to be initialized.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// (The unit test would spot that.)&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; Foo SimpleFoo = &lt;span class="Keyword"&gt;new&lt;/span&gt; Foo(Bar.Zero);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;I&amp;#39;m currently undecided about whether to include static constructors in these classes to ensure lazy initialization. If the type initializer for Foo triggered the initializer of Foo.Constants, we&amp;#39;d be back to square one... but adding static constructors into each of these nested classes sounds like a bit of a pain. The nested classes should call into the type initialization checking as well, to validate they don&amp;#39;t cause any problems themselves.&lt;/p&gt;  &lt;h1&gt;Conclusion&lt;/h1&gt;  &lt;p&gt;I have to say, part of me really doesn&amp;#39;t like either the testing code or the workaround. Both smack of being &lt;em&gt;clever&lt;/em&gt;, which is never a good thing. It&amp;#39;s definitely worth considering whether you could actually just get rid of the type initializer (or part of it) entirely, avoiding maintaining so much static state. It would be nice to be able to detect these type initializer cycles without running anything, simply using static analysis - I&amp;#39;m going to see whether NDepend could do that when I get a chance. The workaround doesn&amp;#39;t feel as neat as Lazy&amp;lt;T&amp;gt;, which is &lt;em&gt;really&lt;/em&gt; what&amp;#39;s called for here - but I don&amp;#39;t trust myself to implement it correctly and efficiently myself.&lt;/p&gt;  &lt;p&gt;So while both are somewhat hacky, they&amp;#39;re better than the alternative: buggy code. That&amp;#39;s what I&amp;#39;m ashamed to say I had in Noda Time, and I don&amp;#39;t think I&amp;#39;d &lt;em&gt;ever&lt;/em&gt; have spotted all the cycles by inspection. It&amp;#39;s worth a try on your own code - see whether you&amp;#39;ve got problems lurking...&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Appendix: Testing code&lt;/h1&gt;  &lt;p&gt;As promised earlier, here&amp;#39;s the code for the production and test classes.&lt;/p&gt;  &lt;h2&gt;TypeInitializationChecker&lt;/h2&gt;  &lt;p&gt;This is in NodaTime.dll itself.&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; TypeInitializationChecker : MarshalByRefObject     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; List&amp;lt;Dependency&amp;gt; dependencies = &lt;span class="Keyword"&gt;null&lt;/span&gt;;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; MethodInfo EntryMethod = &lt;span class="Keyword"&gt;typeof&lt;/span&gt;(TypeInitializationChecker).GetMethod(&lt;span class="String"&gt;&amp;quot;FindDependencies&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; RecordInitializationStart()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (dependencies == &lt;span class="Keyword"&gt;null&lt;/span&gt;)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; 0;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Type previousType = &lt;span class="Keyword"&gt;null&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; frame &lt;span class="Statement"&gt;in&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; StackTrace().GetFrames())     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; method = frame.GetMethod();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (method == EntryMethod)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;break&lt;/span&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; declaringType = method.DeclaringType;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (method == declaringType.TypeInitializer)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (previousType != &lt;span class="Keyword"&gt;null&lt;/span&gt;)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dependencies.Add(&lt;span class="Keyword"&gt;new&lt;/span&gt; Dependency(declaringType, previousType));     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; previousType = declaringType;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; 0;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// Invoked from the unit tests, this finds the dependency chain for a single type&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// by invoking its type initializer.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; Dependency[] FindDependencies(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; name)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dependencies = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;Dependency&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Type type = &lt;span class="Keyword"&gt;typeof&lt;/span&gt;(TypeInitializationChecker).Assembly.GetType(name, &lt;span class="Keyword"&gt;true&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; RuntimeHelpers.RunClassConstructor(type.TypeHandle);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; dependencies.ToArray();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// A simple from/to tuple, which can be marshaled across AppDomains.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Dependency : MarshalByRefObject     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; From { get; &lt;span class="Modifier"&gt;private&lt;/span&gt; set; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; To { get; &lt;span class="Modifier"&gt;private&lt;/span&gt; set; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt; Dependency(Type &lt;span class="Linq"&gt;from&lt;/span&gt;, Type to)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; From = &lt;span class="Linq"&gt;from&lt;/span&gt;.FullName;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; To = to.FullName;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;h2&gt;TypeInitializationTest&lt;/h2&gt;  &lt;p&gt;This is within NodaTime.Test:&lt;/p&gt;  &lt;div class="code"&gt;[TestFixture]    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; TypeInitializationTest     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [Test]     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; BuildInitializerLoops()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Assembly assembly = &lt;span class="Keyword"&gt;typeof&lt;/span&gt;(TypeInitializationChecker).Assembly;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; dependencies = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;TypeInitializationChecker.Dependency&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Test each type in a new AppDomain - we want to see what happens where each type is initialized first.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Note: Namespace prefix check is present to get this to survive in test runners which&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// inject extra types. (Seen with JetBrains.Profiler.Core.Instrumentation.DataOnStack.)&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; type &lt;span class="Statement"&gt;in&lt;/span&gt; assembly.GetTypes().Where(t =&amp;gt; t.FullName.StartsWith(&lt;span class="String"&gt;&amp;quot;NodaTime&amp;quot;&lt;/span&gt;)))     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Note: this won&amp;#39;t be enough to load the assembly in all test runners. In particular, it fails in&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// NCrunch at the moment.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; AppDomainSetup setup = &lt;span class="Keyword"&gt;new&lt;/span&gt; AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory };     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; AppDomain domain = AppDomain.CreateDomain(&lt;span class="String"&gt;&amp;quot;InitializationTest&amp;quot;&lt;/span&gt; + type.Name, AppDomain.CurrentDomain.Evidence, setup);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; helper = (TypeInitializationChecker)domain.CreateInstanceAndUnwrap(assembly.FullName,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;typeof&lt;/span&gt;(TypeInitializationChecker).FullName);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dependencies.AddRange(helper.FindDependencies(type.FullName));     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; lookup = dependencies.ToLookup(d =&amp;gt; d.From, d =&amp;gt; d.To);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// This is less efficient than it might be, but I&amp;#39;m aiming for simplicity: starting at each type&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// which has a dependency, can we make a cycle?&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// See Tarjan&amp;#39;s Algorithm in Wikipedia for ways this could be made more efficient.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// http://en.wikipedia.org/wiki/Tarjan&amp;#39;s_strongly_connected_components_algorithm&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt;&amp;#160;&lt;span class="Linq"&gt;group&lt;/span&gt;&amp;#160;&lt;span class="Statement"&gt;in&lt;/span&gt; lookup)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Stack&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; path = &lt;span class="Keyword"&gt;new&lt;/span&gt; Stack&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CheckForCycles(&lt;span class="Linq"&gt;group&lt;/span&gt;.Key, path, lookup);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; CheckForCycles(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; next, Stack&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; path, ILookup&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; dependencyLookup)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (path.Contains(next))     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Assert.Fail(&lt;span class="String"&gt;&amp;quot;Type initializer cycle: {0}-{1}&amp;quot;&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;.Join(&lt;span class="String"&gt;&amp;quot;-&amp;quot;&lt;/span&gt;, path.Reverse().ToArray()), next);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; path.Push(next);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;foreach&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; candidate &lt;span class="Statement"&gt;in&lt;/span&gt; dependencyLookup[next].Distinct())     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CheckForCycles(candidate, path, dependencyLookup);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; path.Pop();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1808561" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Evil+Code/default.aspx">Evil Code</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Noda+Time/default.aspx">Noda Time</category></item><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>Of memory and strings</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/04/05/of-memory-and-strings.aspx</link><pubDate>Tue, 05 Apr 2011 20:50:47 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1791251</guid><dc:creator>skeet</dc:creator><slash:comments>32</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1791251</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1791251</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/04/05/of-memory-and-strings.aspx#comments</comments><description>&lt;p&gt;This post was provoked by a &lt;a href="http://stackoverflow.com/questions/5435913/net-string-class-alternative"&gt;recent Stack Overflow question&lt;/a&gt; which asked whether there was an efficient representation of ASCII strings in .NET.&lt;/p&gt;  &lt;p&gt;In particular, the questioner wanted to story hundreds of thousands - possibly millions - of strings in memory, and knowing (or assuming) that they all consisted of ASCII characters, he wanted to avoid the waste of space that comes from storing each character in a .NET string as a UTF-16 code unit.&lt;/p&gt;  &lt;p&gt;My answer to the question mostly consisted of saying that I didn&amp;#39;t think it would be worth the effort, and giving some reasons. But the more reasons I gave, the more I thought about the subtleties involved, and that it&amp;#39;s actually quite an interesting case study into memory use in .NET.&lt;/p&gt;  &lt;h2&gt;How are we going to measure object size?&lt;/h2&gt;  &lt;p&gt;If we&amp;#39;re going to work out any sort of benefit from a more compact string representation, we&amp;#39;ll need to be able to calculate how much memory our objects are taking to start with. Rather than work this out in a purely theoretical way, I&amp;#39;ve been running tests using code like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Program     &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;span class="ReferenceType"&gt;string&lt;/span&gt;[] args)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; size = 10000000;     &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;[] array = &lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;object&lt;/span&gt;[size];     &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;long&lt;/span&gt; before = GC.GetTotalMemory(&lt;span class="Keyword"&gt;true&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;for&lt;/span&gt; (&lt;span class="ValueType"&gt;int&lt;/span&gt; i = 0; i &amp;lt; size; i++)&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; {     &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; array[i] = &lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;object&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; &lt;span class="ValueType"&gt;long&lt;/span&gt; after = GC.GetTotalMemory(&lt;span class="Keyword"&gt;true&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;double&lt;/span&gt; diff = after - before;     &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; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Per object: &amp;quot;&lt;/span&gt; + diff / size);     &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;// Stop the GC from messing up our measurements&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; GC.KeepAlive(array);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Obviously that doesn&amp;#39;t take into account factors such as memory used by JITting, or anything that could be going on in other threads, but by using a suitably large number of objects, and by performing the division in floating point arithmetic (to avoid a slight variation making an 11.99999 come out as an 11, when it&amp;#39;s really just a &amp;quot;12 with something else going on&amp;quot;, we can work out the size of objects pretty clearly. The sample above measures the size of a vanilla object, but the code can be adapted very easily.&lt;/p&gt;  &lt;p&gt;The first important thing to point out is that C# doesn&amp;#39;t guarantee the results of this - it isn&amp;#39;t responsible for determining how all of an object is laid out in memory; that&amp;#39;s the runtime&amp;#39;s job. While there are attributes to affect the layout and padding of the &lt;em&gt;data&lt;/em&gt; members of a type in memory, there are other aspects that are out of your control. In this post I won&amp;#39;t use any of the layout attributes - we&amp;#39;ll just use the defaults.&lt;/p&gt;  &lt;p&gt;Not all runtimes are created equal, either. On my laptop I&amp;#39;ve got Mono 2.8, .NET 3.5 and .NET 4, with the two versions of .NET each having the 32-bit (x86) and 64-bit (x64) CLRs. For the sake of simplicity, I&amp;#39;m going to stick with .NET 4 for this post, but I&amp;#39;ll give results for both the x64 and x86 CLRs. To test each of them, I&amp;#39;m compiling with &amp;quot;/platform:x64&amp;quot; or &amp;quot;/platform:x86&amp;quot;.&lt;/p&gt;  &lt;h2&gt;Some simple starter measurements&lt;/h2&gt;  &lt;p&gt;Before I start creating my own types, let&amp;#39;s try a few built-in types, including strings:&lt;/p&gt;  &lt;table border="0" cellspacing="0" cellpadding="2" width="400"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" width="133"&gt;&lt;strong&gt;Type&lt;/strong&gt;&lt;/td&gt;        &lt;td valign="top" width="133"&gt;&lt;strong&gt;x86 size&lt;/strong&gt;&lt;/td&gt;        &lt;td valign="top" width="133"&gt;&lt;strong&gt;x64 size&lt;/strong&gt;&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;object&lt;/td&gt;        &lt;td valign="top" width="133"&gt;12&lt;/td&gt;        &lt;td valign="top" width="133"&gt;24&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;object[]&lt;/td&gt;        &lt;td valign="top" width="133"&gt;16 + length * 4&lt;/td&gt;        &lt;td valign="top" width="133"&gt;32 + length * 8&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;int[]&lt;/td&gt;        &lt;td valign="top" width="133"&gt;12 + length * 4&lt;/td&gt;        &lt;td valign="top" width="133"&gt;28 + length * 4&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;byte[]&lt;/td&gt;        &lt;td valign="top" width="133"&gt;12 + length&lt;/td&gt;        &lt;td valign="top" width="133"&gt;24 + length&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;string&lt;/td&gt;        &lt;td valign="top" width="133"&gt;14 + length * 2&lt;/td&gt;        &lt;td valign="top" width="133"&gt;26 + length * 2&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;Note that all the x86 sizes are rounded up to the nearest 4 bytes, and all x64 sizes are rounded up to the nearest 8 bytes.&lt;/p&gt;  &lt;p&gt;The string numbers are interesting, because strings are the &lt;em&gt;only&lt;/em&gt; non-array types in .NET which vary in size. A long string consists of a single large object in memory. Compare this with Java, where a String is a &amp;quot;normal&amp;quot; type in terms of memory consumption, containing an offset and length into a char array - so a long string consists of a small object referring to a large char array. This distinction will be very important when we come to build an AsciiString type. Another point about measuring string sizes is that it&amp;#39;s relatively tricky to measure the size of an empty string - because even if you use the &amp;quot;new string(&amp;#39;x&amp;#39;, 0)&amp;quot; constructor, the result is still cached - the same reference is returned each time.&lt;/p&gt;  &lt;p&gt;You might be forgiven for looking at the numbers above and thinking that the &amp;quot;overhead&amp;quot; of an object is 12 bytes in x86 and 24 in x64... but that&amp;#39;s not quite right. Let&amp;#39;s build our own straightforward classes and measure them...&lt;/p&gt;  &lt;h2&gt;Custom classes containing primitives&lt;/h2&gt;  &lt;p&gt;Here are six classes, all of which are measured with the same simple test code:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Empty {}     &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; OneInt32 { &lt;span class="ValueType"&gt;int&lt;/span&gt; x; }     &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; TwoInt32 { &lt;span class="ValueType"&gt;int&lt;/span&gt; x, y; }     &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; ThreeInt32 { &lt;span class="ValueType"&gt;int&lt;/span&gt; x, y, z; }     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Mixed1     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; x;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;byte&lt;/span&gt; b1, b2, b3, b4;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; y, z;     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Mixed2     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; x;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;byte&lt;/span&gt; b1;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; y, z;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;byte&lt;/span&gt; b2, b3, b4;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The last case is mostly to check how the CLR handles an &amp;quot;awkward&amp;quot; class declaration, where the int variables won&amp;#39;t naturally be aligned on 4-byte boundaries. The results look odd at first, but we&amp;#39;ll make sense of them in a minute:&lt;/p&gt;  &lt;table border="0" cellspacing="0" cellpadding="2" width="400"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" width="133"&gt;&lt;strong&gt;Type&lt;/strong&gt;&lt;/td&gt;        &lt;td valign="top" width="133"&gt;&lt;strong&gt;x86 size&lt;/strong&gt;&lt;/td&gt;        &lt;td valign="top" width="133"&gt;&lt;strong&gt;x64 size&lt;/strong&gt;&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;Empty&lt;/td&gt;        &lt;td valign="top" width="133"&gt;12&lt;/td&gt;        &lt;td valign="top" width="133"&gt;24&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;OneInt32&lt;/td&gt;        &lt;td valign="top" width="133"&gt;12&lt;/td&gt;        &lt;td valign="top" width="133"&gt;24&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;TwoInt32s&lt;/td&gt;        &lt;td valign="top" width="133"&gt;16&lt;/td&gt;        &lt;td valign="top" width="133"&gt;24&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;ThreeInt32s&lt;/td&gt;        &lt;td valign="top" width="133"&gt;20&lt;/td&gt;        &lt;td valign="top" width="133"&gt;32&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;Mixed1&lt;/td&gt;        &lt;td valign="top" width="133"&gt;24&lt;/td&gt;        &lt;td valign="top" width="133"&gt;32&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="133"&gt;Mixed2&lt;/td&gt;        &lt;td valign="top" width="133"&gt;24&lt;/td&gt;        &lt;td valign="top" width="133"&gt;32&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;A few interesting things to note here:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;There&amp;#39;s a &amp;quot;base&amp;quot; overhead of 8 bytes per object in x86 and 16 per object in x64... given that we can store an Int32 of &amp;quot;real&amp;quot; data in x86 and still have an object size of 12, and likewise we can store two Int32s of real data in x64 and still have an object of x64. &lt;/li&gt;    &lt;li&gt;There&amp;#39;s a &amp;quot;minimum&amp;quot; size of 12 bytes and 24 bytes respectively. In other words, you can&amp;#39;t have a type which is &lt;em&gt;just&lt;/em&gt; the overhead. Note how the &amp;quot;Empty&amp;quot; class takes up the same size as creating instances of Object... there&amp;#39;s effectively some spare room, because the CLR doesn&amp;#39;t like operating on an object with &lt;em&gt;no&lt;/em&gt; data. (Note that a struct with no fields takes up space too, even for local variables.) &lt;/li&gt;    &lt;li&gt;The x86 objects are padded to 4 byte boundaries; on x64 it&amp;#39;s 8 bytes (just as before) &lt;/li&gt;    &lt;li&gt;By default, the CLR is happy to pack fields pretty densely - Mixed2 only took as much space as ThreeInt32. My &lt;em&gt;guess&lt;/em&gt; is that it reorganized the in-memory representation so that the bytes all came after the ints... and that&amp;#39;s what a quick bit of playing around with unsafe pointers suggests too... but I&amp;#39;m not sufficiently comfortable with this sort of thing to say for sure. Frankly, I don&amp;#39;t care... so long as it all works, what we&amp;#39;re interested in is the overall size, not the precise layout. &lt;/li&gt; &lt;/ul&gt;  &lt;h2&gt;So what does an ASCII string look like?&lt;/h2&gt;  &lt;p&gt;In this blog post I&amp;#39;m not actually going to &lt;em&gt;implement&lt;/em&gt; an ASCII string at all (well, not much). I&amp;#39;m merely pointing out what the data structures would look like. However, it&amp;#39;s worth working out what desirable qualities it should have. As far as possible, it should feel like System.String. In particular:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;It should be immutable. &lt;/li&gt;    &lt;li&gt;It should have fast access to individual characters, and the length. &lt;/li&gt;    &lt;li&gt;It should mostly &amp;quot;feel&amp;quot; like an immutable reference type, in that passing a value of type AsciiString around should be cheap, like copying a reference. &lt;/li&gt;    &lt;li&gt;It should use as little memory as possible... less than the equivalent string, or it&amp;#39;s pointless.      &lt;ul&gt;       &lt;li&gt;One caveat to this: in theory that could mean storing 8 characters in every 7 bytes, as ASCII really only uses 7 bits per character. I&amp;#39;m not going to those extremes, but you can think about them if you want. &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;We&amp;#39;re going to store the characters as a byte array. We have three options as to exactly how we handle that byte array:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;We could go the Java way, where several strings share references to the same array. Each string then has an offset and a length to say which bit of the array they&amp;#39;re interested in.      &lt;ul&gt;       &lt;li&gt;Pros: Substring becomes really cheap &lt;/li&gt;        &lt;li&gt;Cons: You can end up having just a tiny substring responsible for keeping a huge character array alive &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;We could go the .NET way, where each string has its own character data, but the buffer may be longer than necessary... so it stores the length too. (A bit like a List&amp;lt;T&amp;gt;.)      &lt;ul&gt;       &lt;li&gt;Pros: Can potentially make building strings cheap, if you just keep whatever potentially oversized buffer you&amp;#39;ve already got. &lt;/li&gt;        &lt;li&gt;Cons: Wasted space for the unused part of the array, and a field for the length. &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;We could just have a byte array of exactly the right size - and it already knows its size. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I&amp;#39;m going to assume the third option here. So all the data our type needs is a byte array. That&amp;#39;s going to be pretty cheap... we hope. Let&amp;#39;s look at what we can build.&lt;/p&gt;  &lt;h2&gt;Option 1: A simple class&lt;/h2&gt;  &lt;p&gt;To give a &lt;em&gt;flavour&lt;/em&gt; of the implementation, I&amp;#39;ve decided to implement four members for each option:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;A way of creating an AsciiString from a regular string &lt;/li&gt;    &lt;li&gt;The Substring overload with both a start and length &lt;/li&gt;    &lt;li&gt;The Length property &lt;/li&gt;    &lt;li&gt;The indexer returning a char &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Hopefully that will give enough of an idea of what&amp;#39;s going on to be useful. Note that these aren&amp;#39;t production-quality implementations at all... none of the code has ever been &lt;em&gt;run&lt;/em&gt; at all. I &lt;em&gt;have&lt;/em&gt; made sure it compiles, so just be grateful for that :)&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.Text;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; AsciiString     &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;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;byte&lt;/span&gt;[] data;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; AsciiString(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; text)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// TODO: Rather more data validation etc!&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; data = Encoding.ASCII.GetBytes(text);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;private&lt;/span&gt; AsciiString(&lt;span class="ValueType"&gt;byte&lt;/span&gt;[] data)     &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;// This constructor is private: we can trust that it&amp;#39;s been called&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;// by code which isn&amp;#39;t going to modify the contents of the array&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;// afterwards.&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Keyword"&gt;this&lt;/span&gt;.data = data;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt; AsciiString Substring(&lt;span class="ValueType"&gt;int&lt;/span&gt; startIndex, &lt;span class="ValueType"&gt;int&lt;/span&gt; length)     &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; (startIndex &amp;lt; 0 || startIndex &amp;gt; data.Length)     &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; ArgumentOutOfRangeException(&lt;span class="String"&gt;&amp;quot;startIndex&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; &lt;span class="Statement"&gt;if&lt;/span&gt; (startIndex + length &amp;gt; data.Length)     &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; ArgumentOutOfRangeException(&lt;span class="String"&gt;&amp;quot;length&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; &lt;span class="ValueType"&gt;byte&lt;/span&gt;[] newData = &lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;byte&lt;/span&gt;[length];     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Buffer.BlockCopy(data, startIndex, newData, 0, length);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; AsciiString(newData);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; Length { get { &lt;span class="Statement"&gt;return&lt;/span&gt; data.Length; } }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;char&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;this&lt;/span&gt;[&lt;span class="ValueType"&gt;int&lt;/span&gt; position] { get { &lt;span class="Statement"&gt;return&lt;/span&gt; (&lt;span class="ValueType"&gt;char&lt;/span&gt;) data[position]; } }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// etc...&lt;/span&gt;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Hopefully this is pretty straightforward - it&amp;#39;s meant to be the most &amp;quot;obvious&amp;quot; solution. Note that we&amp;#39;ve not got the nice locality of reference which the real String class has - it&amp;#39;s possible that the an AsciiString could end up with its backing array a long way away in memory, so a indexer operation for a single character could end up with three cache misses - one for the AsciiString object, one for part of the data array storing the length (for argument validation) and one for the part of the data array containing the character we&amp;#39;re looking for. That may be unlikely, and it&amp;#39;s not the kind of thing I &lt;em&gt;normally &lt;/em&gt;think about - but it&amp;#39;s probably the kind of thing the BCL team pay a lot of attention to.&lt;/p&gt;  &lt;p&gt;We get the same &amp;quot;immutable reference type&amp;quot; behaviour present in the normal string type, however - you can have a null AsciiString reference just as normal, any assignments will just be reference assignments, etc.&lt;/p&gt;  &lt;p&gt;What about the size though? There are two objects to consider:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The array, of size 12 + length or 24 + length (x86 and x64 respectively; rounded up to 4 or 8 bytes as well) &lt;/li&gt;    &lt;li&gt;The object itself, of size 12 or 24 &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So we&amp;#39;ve got a total size of 24 + length or 48 + length, depending on architecture. To show how the break-even point works, here&amp;#39;s a little table showing the sizes of string and AsciiString for various sizes on both architectures:&lt;/p&gt;  &lt;table border="0" cellspacing="0" cellpadding="2" width="500"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" width="99"&gt;Length&lt;/td&gt;        &lt;td valign="top" width="98"&gt;string-x86&lt;/td&gt;        &lt;td valign="top" width="98"&gt;string-x64&lt;/td&gt;        &lt;td valign="top" width="102"&gt;AsciiString-x86&lt;/td&gt;        &lt;td valign="top" width="101"&gt;AsciiString-x64&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="98"&gt;0&lt;/td&gt;        &lt;td valign="top" width="98"&gt;16&lt;/td&gt;        &lt;td valign="top" width="98"&gt;32&lt;/td&gt;        &lt;td valign="top" width="103"&gt;24&lt;/td&gt;        &lt;td valign="top" width="101"&gt;48&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;1&lt;/td&gt;        &lt;td valign="top" width="98"&gt;16&lt;/td&gt;        &lt;td valign="top" width="98"&gt;32&lt;/td&gt;        &lt;td valign="top" width="104"&gt;28&lt;/td&gt;        &lt;td valign="top" width="102"&gt;56&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="98"&gt;2&lt;/td&gt;        &lt;td valign="top" width="97"&gt;20&lt;/td&gt;        &lt;td valign="top" width="97"&gt;32&lt;/td&gt;        &lt;td valign="top" width="104"&gt;28&lt;/td&gt;        &lt;td valign="top" width="103"&gt;56&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;3&lt;/td&gt;        &lt;td valign="top" width="97"&gt;20&lt;/td&gt;        &lt;td valign="top" width="97"&gt;32&lt;/td&gt;        &lt;td valign="top" width="104"&gt;28&lt;/td&gt;        &lt;td valign="top" width="103"&gt;56&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;4&lt;/td&gt;        &lt;td valign="top" width="97"&gt;24&lt;/td&gt;        &lt;td valign="top" width="97"&gt;40&lt;/td&gt;        &lt;td valign="top" width="104"&gt;28&lt;/td&gt;        &lt;td valign="top" width="103"&gt;56&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;5&lt;/td&gt;        &lt;td valign="top" width="97"&gt;24&lt;/td&gt;        &lt;td valign="top" width="98"&gt;40&lt;/td&gt;        &lt;td valign="top" width="105"&gt;32&lt;/td&gt;        &lt;td valign="top" width="104"&gt;56&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;6&lt;/td&gt;        &lt;td valign="top" width="97"&gt;28&lt;/td&gt;        &lt;td valign="top" width="98"&gt;40&lt;/td&gt;        &lt;td valign="top" width="105"&gt;32&lt;/td&gt;        &lt;td valign="top" width="104"&gt;56&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;7&lt;/td&gt;        &lt;td valign="top" width="97"&gt;28&lt;/td&gt;        &lt;td valign="top" width="98"&gt;40&lt;/td&gt;        &lt;td valign="top" width="105"&gt;32&lt;/td&gt;        &lt;td valign="top" width="104"&gt;56&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;8&lt;/td&gt;        &lt;td valign="top" width="97"&gt;32&lt;/td&gt;        &lt;td valign="top" width="98"&gt;48&lt;/td&gt;        &lt;td valign="top" width="105"&gt;32&lt;/td&gt;        &lt;td valign="top" width="104"&gt;56&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;9&lt;/td&gt;        &lt;td valign="top" width="97"&gt;32&lt;/td&gt;        &lt;td valign="top" width="98"&gt;48&lt;/td&gt;        &lt;td valign="top" width="105"&gt;36&lt;/td&gt;        &lt;td valign="top" width="104"&gt;64&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;10&lt;/td&gt;        &lt;td valign="top" width="97"&gt;36&lt;/td&gt;        &lt;td valign="top" width="98"&gt;48&lt;/td&gt;        &lt;td valign="top" width="105"&gt;36&lt;/td&gt;        &lt;td valign="top" width="104"&gt;64&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;...&lt;/td&gt;        &lt;td valign="top" width="97"&gt;..&lt;/td&gt;        &lt;td valign="top" width="98"&gt;...&lt;/td&gt;        &lt;td valign="top" width="105"&gt;...&lt;/td&gt;        &lt;td valign="top" width="104"&gt;...&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;16&lt;/td&gt;        &lt;td valign="top" width="97"&gt;48&lt;/td&gt;        &lt;td valign="top" width="98"&gt;64&lt;/td&gt;        &lt;td valign="top" width="105"&gt;40&lt;/td&gt;        &lt;td valign="top" width="104"&gt;64&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;24&lt;/td&gt;        &lt;td valign="top" width="97"&gt;64&lt;/td&gt;        &lt;td valign="top" width="98"&gt;80&lt;/td&gt;        &lt;td valign="top" width="105"&gt;48&lt;/td&gt;        &lt;td valign="top" width="104"&gt;72&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;32&lt;/td&gt;        &lt;td valign="top" width="97"&gt;80&lt;/td&gt;        &lt;td valign="top" width="98"&gt;96&lt;/td&gt;        &lt;td valign="top" width="105"&gt;56&lt;/td&gt;        &lt;td valign="top" width="104"&gt;80&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;As you can see, the break-even point in x86 is at length 10; in x64 it&amp;#39;s at length 16. After that, we start winning - as we&amp;#39;d expect. The penalty for very small strings is quite hefty though - you&amp;#39;d really better hope you didn&amp;#39;t have lots of single-character strings, taking 56 bytes each in x64.&lt;/p&gt;  &lt;p&gt;Let&amp;#39;s see if we can do better...&lt;/p&gt;  &lt;h2&gt;Option 2: A simple struct&lt;/h2&gt;  &lt;p&gt;A lot of the overhead here has come from the fact that we&amp;#39;ve got an object which only has a single field. The field is all we&amp;#39;re interested in... why are we bothering with all the overhead of the object? Let&amp;#39;s make it a struct instead, effectively inlining that field wherever we use the type. Assignment, passing arguments to methods etc will still only be copying a reference - it&amp;#39;s just the reference will be the byte array rather than a wrapper object.&lt;/p&gt;  &lt;p&gt;It all sounds good, but there are two snags:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The value can never be null; that &lt;em&gt;at least&lt;/em&gt; diverges from the familiar string behaviour &lt;/li&gt;    &lt;li&gt;We won&amp;#39;t be able to prevent code from creating an instance of our struct with new AsciiString() - and that won&amp;#39;t be good. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;We can actually pit these two downsides against each other by making the &amp;quot;default&amp;quot; value a pseudo-null value... we can even throw NullReferenceException just as if it were a reference type. We don&amp;#39;t even need to do any work in order to get that NullReferenceException - every member is going to use the data array anyway, and dereferencing that will automatically throw an exception. We might want to change things around a bit to make that the very &lt;em&gt;first&lt;/em&gt; thing that can throw an exception, but that&amp;#39;s all.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s nasty, but it appeals very slightly. In an evil kind of way. It makes things slightly more familiar, but at the cost of being generally weird in other ways.&lt;/p&gt;  &lt;p&gt;We still need to be able to check whether an AsciiString value &lt;em&gt;is&lt;/em&gt; the logical null value. I&amp;#39;ll add an IsNull property for that purpose. (An alternative would be HasValue, but that would be confusing with Nullable&amp;lt;T&amp;gt;.)&lt;/p&gt;  &lt;p&gt;Most of the code remains untouched - it looks 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;struct&lt;/span&gt; AsciiString     &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;readonly&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;byte&lt;/span&gt;[] data;     &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="ValueType"&gt;bool&lt;/span&gt; IsNull { get { &lt;span class="Statement"&gt;return&lt;/span&gt; data == &lt;span class="Keyword"&gt;null&lt;/span&gt;; } }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Remainder of code as before&lt;/span&gt;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Now let&amp;#39;s look at the sizes, which should be a lot more favourable than before. Note that I had to change the size-checking code to create an array of type AsciiStruct[] instead of object[] to avoid boxing. Should we take the size of the array itself into consideration when computing the size of the AsciiString? We haven&amp;#39;t when working out the size of string... in each case the size of any individual element will be the size of a reference. For the table below, I &lt;em&gt;haven&amp;#39;t&lt;/em&gt; included it... but bear in mind that this form of measurement would count the size of most value types (int etc) as 0. It just goes to show that when you talk about the size of a data type, you really need to be &lt;em&gt;very&lt;/em&gt; precise in what you mean.&lt;/p&gt;  &lt;table border="0" cellspacing="0" cellpadding="2" width="500"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" width="99"&gt;Length&lt;/td&gt;        &lt;td valign="top" width="98"&gt;string-x86&lt;/td&gt;        &lt;td valign="top" width="98"&gt;string-x64&lt;/td&gt;        &lt;td valign="top" width="102"&gt;AsciiString-x86&lt;/td&gt;        &lt;td valign="top" width="101"&gt;AsciiString-x64&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="98"&gt;0&lt;/td&gt;        &lt;td valign="top" width="98"&gt;16&lt;/td&gt;        &lt;td valign="top" width="98"&gt;32&lt;/td&gt;        &lt;td valign="top" width="103"&gt;12&lt;/td&gt;        &lt;td valign="top" width="101"&gt;24&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;1&lt;/td&gt;        &lt;td valign="top" width="98"&gt;16&lt;/td&gt;        &lt;td valign="top" width="98"&gt;32&lt;/td&gt;        &lt;td valign="top" width="104"&gt;16&lt;/td&gt;        &lt;td valign="top" width="102"&gt;32&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="98"&gt;2&lt;/td&gt;        &lt;td valign="top" width="97"&gt;20&lt;/td&gt;        &lt;td valign="top" width="97"&gt;32&lt;/td&gt;        &lt;td valign="top" width="104"&gt;16&lt;/td&gt;        &lt;td valign="top" width="103"&gt;32&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;3&lt;/td&gt;        &lt;td valign="top" width="97"&gt;20&lt;/td&gt;        &lt;td valign="top" width="97"&gt;32&lt;/td&gt;        &lt;td valign="top" width="104"&gt;16&lt;/td&gt;        &lt;td valign="top" width="103"&gt;32&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;4&lt;/td&gt;        &lt;td valign="top" width="97"&gt;24&lt;/td&gt;        &lt;td valign="top" width="97"&gt;40&lt;/td&gt;        &lt;td valign="top" width="104"&gt;16&lt;/td&gt;        &lt;td valign="top" width="103"&gt;32&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;5&lt;/td&gt;        &lt;td valign="top" width="97"&gt;24&lt;/td&gt;        &lt;td valign="top" width="98"&gt;40&lt;/td&gt;        &lt;td valign="top" width="105"&gt;20&lt;/td&gt;        &lt;td valign="top" width="104"&gt;32&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;6&lt;/td&gt;        &lt;td valign="top" width="97"&gt;28&lt;/td&gt;        &lt;td valign="top" width="98"&gt;40&lt;/td&gt;        &lt;td valign="top" width="105"&gt;20&lt;/td&gt;        &lt;td valign="top" width="104"&gt;32&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;7&lt;/td&gt;        &lt;td valign="top" width="97"&gt;28&lt;/td&gt;        &lt;td valign="top" width="98"&gt;40&lt;/td&gt;        &lt;td valign="top" width="105"&gt;20&lt;/td&gt;        &lt;td valign="top" width="104"&gt;32&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;8&lt;/td&gt;        &lt;td valign="top" width="97"&gt;32&lt;/td&gt;        &lt;td valign="top" width="98"&gt;48&lt;/td&gt;        &lt;td valign="top" width="105"&gt;20&lt;/td&gt;        &lt;td valign="top" width="104"&gt;32&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;9&lt;/td&gt;        &lt;td valign="top" width="97"&gt;32&lt;/td&gt;        &lt;td valign="top" width="98"&gt;48&lt;/td&gt;        &lt;td valign="top" width="105"&gt;24&lt;/td&gt;        &lt;td valign="top" width="104"&gt;40&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;10&lt;/td&gt;        &lt;td valign="top" width="97"&gt;36&lt;/td&gt;        &lt;td valign="top" width="98"&gt;48&lt;/td&gt;        &lt;td valign="top" width="105"&gt;24&lt;/td&gt;        &lt;td valign="top" width="104"&gt;40&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;...&lt;/td&gt;        &lt;td valign="top" width="97"&gt;..&lt;/td&gt;        &lt;td valign="top" width="98"&gt;...&lt;/td&gt;        &lt;td valign="top" width="105"&gt;...&lt;/td&gt;        &lt;td valign="top" width="104"&gt;...&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;16&lt;/td&gt;        &lt;td valign="top" width="97"&gt;48&lt;/td&gt;        &lt;td valign="top" width="98"&gt;64&lt;/td&gt;        &lt;td valign="top" width="105"&gt;28&lt;/td&gt;        &lt;td valign="top" width="104"&gt;40&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;24&lt;/td&gt;        &lt;td valign="top" width="97"&gt;64&lt;/td&gt;        &lt;td valign="top" width="98"&gt;80&lt;/td&gt;        &lt;td valign="top" width="105"&gt;36&lt;/td&gt;        &lt;td valign="top" width="104"&gt;48&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="97"&gt;32&lt;/td&gt;        &lt;td valign="top" width="97"&gt;80&lt;/td&gt;        &lt;td valign="top" width="98"&gt;96&lt;/td&gt;        &lt;td valign="top" width="105"&gt;44&lt;/td&gt;        &lt;td valign="top" width="104"&gt;56&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;This time, unsurprisingly, AsciiString is &lt;em&gt;always&lt;/em&gt; more space-efficient than the normal string. It just takes a certain amount of holding our noses. Speaking of which...&lt;/p&gt;  &lt;h2&gt;Option 3: Extension methods on byte[]&lt;/h2&gt;  &lt;p&gt;Suppose we really, really want to have &amp;quot;proper&amp;quot; null references. We don&amp;#39;t really &lt;em&gt;need&lt;/em&gt; the struct. We could treat &lt;em&gt;any&lt;/em&gt; byte array as an array of ASCII characters, with extension 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;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; ByteArrayExtensions    &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;byte&lt;/span&gt;[] Substring(&lt;span class="Keyword"&gt;this&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;byte&lt;/span&gt;[] data, &lt;span class="ValueType"&gt;int&lt;/span&gt; startIndex, &lt;span class="ValueType"&gt;int&lt;/span&gt; length)    &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; (startIndex &amp;lt; 0 || startIndex &amp;gt; data.Length)    &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; ArgumentOutOfRangeException(&lt;span class="String"&gt;&amp;quot;startIndex&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; &lt;span class="Statement"&gt;if&lt;/span&gt; (startIndex + length &amp;gt; data.Length)    &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; ArgumentOutOfRangeException(&lt;span class="String"&gt;&amp;quot;length&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; &lt;span class="ValueType"&gt;byte&lt;/span&gt;[] newData = &lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;byte&lt;/span&gt;[length];    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Buffer.BlockCopy(data, startIndex, newData, 0, length);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; newData;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The size is the same as with option 2 - in both cases there&amp;#39;s just the byte array, basically. This option is truly horrible in many ways though:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;You can no longer tell in your code (just through typing) what&amp;#39;s meant to be an AsciiString and what isn&amp;#39;t&lt;/li&gt;    &lt;li&gt;Kiss immutability goodbye&lt;/li&gt;    &lt;li&gt;We can&amp;#39;t guarantee that all the characters will be valid ASCII any more&lt;/li&gt;    &lt;li&gt;We can&amp;#39;t add extension properties or extension indexers&lt;/li&gt;    &lt;li&gt;We can&amp;#39;t make it implement the interfaces we want it to&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Obviously, we&amp;#39;d never take this route. I just thought I&amp;#39;d include it for a regular dose of evil-ness.&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;Implementing an ASCII-only string representation &lt;em&gt;sounds&lt;/em&gt; like it should be an obvious win in terms of memory, at the cost of doing a lot of work that&amp;#39;s already been done for us in String. However, the most obvious implementation takes a while to break even in memory usage, compared with the normal string type, due to the &amp;quot;special&amp;quot; nature of string within the CLR. We can&amp;#39;t mimic the &amp;quot;stretchiness&amp;quot; of string ourselves. The BCL/CLR teams could, of course, if they &lt;em&gt;really &lt;/em&gt;wanted to. I&amp;#39;m not holding my breath though.&lt;/p&gt;  &lt;p&gt;If we&amp;#39;re dead keen on saving space at the cost of some design wonkiness, we can use a value type instead of a reference type. Other than nullity, it works pretty well... but you have all the disadvantages which go with value types, such as the unavoidable parameterless constructor and the need to watch out for boxing.&lt;/p&gt;  &lt;p&gt;Aside from anything else, I hope this was useful as a delve into how much space objects actually take up in .NET - and as a way of highlighting the extra memory used when running in the x64 CLR.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1791251" 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/Evil+Code/default.aspx">Evil Code</category></item><item><title>Evil code - overload resolution workaround</title><link>http://msmvps.com/blogs/jon_skeet/archive/2010/11/02/evil-code-overload-resolution-workaround.aspx</link><pubDate>Tue, 02 Nov 2010 08:50:15 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1781370</guid><dc:creator>skeet</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1781370</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1781370</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2010/11/02/evil-code-overload-resolution-workaround.aspx#comments</comments><description>&lt;p&gt;Another quick break from asynchrony, because I can&amp;#39;t resist blogging about this thoroughly evil idea which came to me on the train.&lt;/p&gt;  &lt;p&gt;Your task: to write three static methods such that this C# 4 code:&lt;/p&gt;  &lt;div class="code"&gt;&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; Foo&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Foo&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Foo&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;?&amp;gt;();     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;resolves one call to each of them - and will act appropriately for any non-nullable value type, reference type, and nullable value type respectively.&lt;/p&gt;  &lt;p&gt;You&amp;#39;re not allowed to change anything in the Main method above, and they have to just be methods - no tricks using delegate-type fields, for example. (I don&amp;#39;t know whether such tricks would help you or not, admittedly. I suspect not.) It can&amp;#39;t just call one method which then determines other methods to call at execution time - we want to resolve this at &lt;em&gt;compile&lt;/em&gt; time.&lt;/p&gt;  &lt;p&gt;If you want to try this for yourself, look away now. I&amp;#39;ve deliberately included an attempt which &lt;em&gt;won&amp;#39;t&lt;/em&gt; work below, so that hopefully you won&amp;#39;t see the working solution accidentally.&lt;/p&gt;  &lt;h2&gt;The simple (but failed) attempt&lt;/h2&gt;  &lt;p&gt;You might initially want to try this:&lt;/p&gt;  &lt;div class="code"&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; Foo&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;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Foo&amp;lt;T&amp;gt;() &lt;span class="Linq"&gt;where&lt;/span&gt; T : &lt;span class="ValueType"&gt;struct&lt;/span&gt; {}     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Let&amp;#39;s hope the compiler thinks this is &amp;quot;worse&amp;quot;&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// than the others because it has no constraints&lt;/span&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; Foo&amp;lt;T&amp;gt;()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Foo&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Foo&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;?&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Foo&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&amp;#160; &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;That&amp;#39;s no good at all. I wrote about &lt;i&gt;why&lt;/i&gt; it&amp;#39;s no good &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2010/10/28/overloading-and-generic-constraints.aspx"&gt;in this very blog, last week&lt;/a&gt;. The compiler only checks generic constraints on the type parameters &lt;em&gt;after&lt;/em&gt; overload resolution.&lt;/p&gt;  &lt;p&gt;Fail.&lt;/p&gt;  &lt;h2&gt;First steps towards a solution&lt;/h2&gt;  &lt;p&gt;You may remember that the compiler &lt;em&gt;does&lt;/em&gt; check that &lt;em&gt;parameter&lt;/em&gt; types make sense when working out the candidate set. That gives us some hope... all we&amp;#39;ve got to do is propagate our desired constraints into parameters.&lt;/p&gt;  &lt;p&gt;Ah... but we&amp;#39;re calling a method with no arguments. So there can&amp;#39;t be any parameters, right?&lt;/p&gt;  &lt;p&gt;Wrong. We can have an &lt;em&gt;optional&lt;/em&gt; parameter. Okay, now we&amp;#39;re getting somewhere. What type of parameter can we apply to force a parameter to only be valid if a generic type parameter T is a non-nullable type? The simplest option which occurs is to use Nullable&amp;lt;T&amp;gt; - that has an appropriate constraint. So, we end up with a method like &lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Foo&amp;lt;T&amp;gt;(T? ignored = &lt;span class="Modifier"&gt;default&lt;/span&gt;(T?)) &lt;span class="Linq"&gt;where&lt;/span&gt; T : &lt;span class="ValueType"&gt;struct &lt;/span&gt;{} &lt;/div&gt;  &lt;p&gt;Okay, so that&amp;#39;s the first call sorted out - it will be valid for the above method, but neither of the others will.&lt;/p&gt;  &lt;p&gt;What about the reference type parameter? That&amp;#39;s slightly trickier - I can&amp;#39;t think of any common generic types in the framework which require their type parameters to be reference types. There may be one, of course - I just can&amp;#39;t think of one offhand. Fortunately, it&amp;#39;s easy to declare such a type ourselves, and then use it in another method:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; ClassConstraint&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;&amp;#160; &lt;br /&gt;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Foo&amp;lt;T&amp;gt;(ClassConstraint&amp;lt;T&amp;gt; ignored = &lt;span class="Modifier"&gt;default&lt;/span&gt;(ClassConstraint&amp;lt;T&amp;gt;))&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;where&lt;/span&gt; T : &lt;span class="ReferenceType"&gt;class&lt;/span&gt; {} &lt;/div&gt;  &lt;p&gt;Great. Just one more to go. Unfortunately, there&amp;#39;s no constraint which only satisfies nullable value types... Hmm.&lt;/p&gt;  &lt;h2&gt;The awkwardness of nullable value types&lt;/h2&gt;  &lt;p&gt;We want to effectively say, &amp;quot;Use this method if neither of the other two work - but use the other methods in preference.&amp;quot; Now if we weren&amp;#39;t already using optional parameters, we could potentially do it that way - by introducing a single optional parameter, we could have a method which was still &lt;em&gt;valid&lt;/em&gt; for the other calls, but would be deemed &amp;quot;worse&amp;quot; by overload resolution. Unfortunately, overload resolution takes a binary view of optional parameters: either the compiler is having to fill in some parameters itself, or it&amp;#39;s not. It doesn&amp;#39;t think that filling in two parameter is &amp;quot;worse&amp;quot; than only filling in one.&lt;/p&gt;  &lt;p&gt;Luckily, there&amp;#39;s a way out... inheritance to the rescue! (It&amp;#39;s not often you&amp;#39;ll hear me say that.)&lt;/p&gt;  &lt;p&gt;The compiler will always prefer applicable methods in a derived class to applicable methods in a base class, even if they&amp;#39;d otherwise be better. So we can write a parameterless method with no type constraints at all in a base class. We can even keep it as a private method, so long as we make the derived class a nested type within its own base class.&lt;/p&gt;  &lt;h2&gt;Final solution&lt;/h2&gt;  &lt;p&gt;This leads to the final code - this time with diagnostics to prove it works:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;    &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Base    &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; Foo&amp;lt;T&amp;gt;()    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;nullable value type&amp;quot;&lt;/span&gt;);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;class&lt;/span&gt; Test : Base    &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;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Foo&amp;lt;T&amp;gt;(T? ignored = &lt;span class="Modifier"&gt;default&lt;/span&gt;(T?))    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;where&lt;/span&gt; T : &lt;span class="ValueType"&gt;struct&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; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;non-nullable value type&amp;quot;&lt;/span&gt;);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;class&lt;/span&gt; ClassConstraint&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;&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="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Foo&amp;lt;T&amp;gt;(ClassConstraint&amp;lt;T&amp;gt; ignored = &lt;span class="Modifier"&gt;default&lt;/span&gt;(ClassConstraint&amp;lt;T&amp;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; &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;&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; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;reference type&amp;quot;&lt;/span&gt;);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &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;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {    &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; Foo&amp;lt;&lt;span class="ValueType"&gt;int&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; Foo&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; Foo&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;?&amp;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; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;And the output...&lt;/p&gt;  &lt;div class="code"&gt;non-nullable value type   &lt;br /&gt;reference type    &lt;br /&gt;nullable value type &lt;/div&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;This is possibly the most horrible code I&amp;#39;ve ever written.&lt;/p&gt;  &lt;p&gt;Please, &lt;em&gt;please&lt;/em&gt; don&amp;#39;t use it in real life. Use different method names or something like that.&lt;/p&gt;  &lt;p&gt;Still, it&amp;#39;s a fun little puzzle, isn&amp;#39;t it?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1781370" 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/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>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>Evil Code of the Day: variance and overloading</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/07/13/evil-code-of-the-day-variance-and-overloading.aspx</link><pubDate>Mon, 13 Jul 2009 16:10:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1700112</guid><dc:creator>skeet</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1700112</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1700112</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/07/13/evil-code-of-the-day-variance-and-overloading.aspx#comments</comments><description>&lt;p&gt;(Note that this kind of breakage was &lt;a href="http://blogs.msdn.com/ericlippert/archive/2007/11/02/covariance-and-contravariance-in-c-part-nine-breaking-changes.aspx"&gt;mentioned a long time ago in Eric Lippert&amp;#39;s blog&lt;/a&gt;, although not in this exact form.)&lt;/p&gt;
&lt;p&gt;Whenever a conversion becomes available where it wasn&amp;#39;t before, overload resolution can change its behaviour. From C# 1 to C# 2 this happened due to delegate variance with method group conversions - now the same thing is true for generic variance for interfaces.&lt;/p&gt;
&lt;p&gt;What does the following code print?&lt;/p&gt;
&lt;div class="code"&gt; &lt;span class="Namespace"&gt;using&lt;/span&gt;&amp;nbsp;System;&lt;br /&gt; &lt;span class="Namespace"&gt;using&lt;/span&gt;&amp;nbsp;System.Collections.Generic;&lt;br /&gt; &lt;br /&gt; &lt;span class="ReferenceType"&gt;class&lt;/span&gt;&amp;nbsp;Base&lt;br /&gt; {&lt;br /&gt; &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;&amp;nbsp;Foo(IEnumerable&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;&amp;nbsp;strings)&lt;br /&gt; &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;Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Strings&amp;quot;&lt;/span&gt;);&lt;br /&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; &lt;span class="ReferenceType"&gt;class&lt;/span&gt;&amp;nbsp;Derived&amp;nbsp;:&amp;nbsp;Base&lt;br /&gt; {&lt;br /&gt; &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;&amp;nbsp;Foo(IEnumerable&amp;lt;&lt;span class="ReferenceType"&gt;object&lt;/span&gt;&amp;gt;&amp;nbsp;objects)&lt;br /&gt; &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;Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Objects&amp;quot;&lt;/span&gt;);&lt;br /&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; &lt;span class="ReferenceType"&gt;class&lt;/span&gt;&amp;nbsp;Test&lt;br /&gt; {&lt;br /&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;void&lt;/span&gt;&amp;nbsp;Main()&lt;br /&gt; &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;List&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;&amp;nbsp;strings&amp;nbsp;=&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;nbsp;List&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;();&lt;br /&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;nbsp;Derived().Foo(strings);&lt;br /&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt; } &lt;/div&gt;
&lt;p&gt;The correct answer is &amp;quot;it depends on which version of C# &lt;em&gt;and&lt;/em&gt; .NET framework you&amp;#39;re using.&amp;quot;&lt;/p&gt;
&lt;p&gt;If you&amp;#39;re using C# 4.0 and .NET 4.0, then IEnumerable&amp;lt;T&amp;gt; is covariant: there&amp;#39;s an implicit conversion from IEnumerable&amp;lt;string&amp;gt; to IEnumerable&amp;lt;object&amp;gt;, so the derived overload is used.&lt;/p&gt;
&lt;p&gt;If you&amp;#39;re using C# 4.0 but .NET 3.5 or earlier then the compiler still knows about variance in general, but the interface in the framework doesn&amp;#39;t have the appropriate metadata to indicate it, so there&amp;#39;s no conversion available, and the base class overload is used.&lt;/p&gt;
&lt;p&gt;If you&amp;#39;re using C# 3.0 or earlier then the compiler doesn&amp;#39;t know about generic variance at all, so again the base class overload is used.&lt;/p&gt;
&lt;p&gt;So, this is a breaking change, and a fairly subtle one at that - and unlike the method group conversion in .NET 2.0, the compiler in .NET 4.0 beta 1 doesn&amp;#39;t issue a warning about it. I&amp;#39;ll edit this post when there&amp;#39;s an appropriate Connect ticket about it...&lt;/p&gt;
&lt;p&gt;In general though, I&amp;#39;d say it&amp;#39;s worth avoiding overloading a method declared in a base class unless you really have to. In particular, overloading it using the same number of parameters but more general ones seems to be a recipe for unreadable code.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1700112" 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/C_2300_+4/default.aspx">C# 4</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Evil+Code/default.aspx">Evil Code</category></item></channel></rss>