<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://msmvps.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Jon Skeet: Coding Blog : C#, Wacky Ideas</title><link>http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/Wacky+Ideas/default.aspx</link><description>Tags: C#, Wacky Ideas</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><item><title>Eduasync part 13: first look at coroutines with async</title><link>http://msmvps.com/blogs/jon_skeet/archive/2011/06/22/eduasync-part-13-first-look-at-coroutines-with-async.aspx</link><pubDate>Wed, 22 Jun 2011 20:37:30 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1795089</guid><dc:creator>skeet</dc:creator><slash:comments>14</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1795089</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1795089</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2011/06/22/eduasync-part-13-first-look-at-coroutines-with-async.aspx#comments</comments><description>&lt;p&gt;(This part covers project 18 in the &lt;a href="http://code.google.com/p/eduasync/source/browse/"&gt;source code&lt;/a&gt;.)&lt;/p&gt;  &lt;p&gt;As I mentioned in earlier parts, the &amp;quot;awaiting&amp;quot; part of async methods is in no way limited to tasks. So long as we have a suitable GetAwaiter() method which returns a value of a type which in turn has suitable methods on it, the compiler doesn&amp;#39;t really care what&amp;#39;s going on. It&amp;#39;s time to exploit that to implement some form of &lt;a href="http://en.wikipedia.org/wiki/Coroutine"&gt;coroutines&lt;/a&gt; in C#.&lt;/p&gt;  &lt;h3&gt;Introduction to coroutines&lt;/h3&gt;  &lt;p&gt;The fundamental idea of coroutines is to have multiple methods executing cooperatively, each of them maintaining their position within the coroutine when they yield to another. You can &lt;em&gt;almost&lt;/em&gt; think of them as executing in multiple threads, with only one thread actually &lt;em&gt;running&lt;/em&gt; at a time, and signalling between the different threads to control flow. However, we don&amp;#39;t really need multiple threads once we&amp;#39;ve got continuations - we can have a single thread with a complex flow of continuations, and still only a very short &amp;quot;real&amp;quot; stack. (The control flow is stored in normal collections instead of being implicit on the thread&amp;#39;s stack.)&lt;/p&gt;  &lt;p&gt;Coroutines were already feasible in C# through the use of iterator blocks, but the async feature of C# allows a slightly more natural way of expressing them, in my view. (The linked Wikipedia page gives a sketch of how coroutines can be built on top of &lt;em&gt;generators&lt;/em&gt;, which in the general concept that iterator blocks implement in C#.)&lt;/p&gt;  &lt;p&gt;I have implemented various flavours of coroutines in Eduasync. It&amp;#39;s possible that some (all?) of them shouldn&amp;#39;t &lt;em&gt;strictly &lt;/em&gt;be called coroutines, but they&amp;#39;re close enough to the real thing in feeling. This is far from an exhaustive set of approaches. Once you&amp;#39;ve got the basic idea of what I&amp;#39;m doing, you may well want to experiment with your own implementations.&lt;/p&gt;  &lt;p&gt;I&amp;#39;m &lt;em&gt;not&lt;/em&gt; going to claim that the use of coroutines in any of my examples really makes any sense in terms of making real tasks easier. This is &lt;em&gt;purely&lt;/em&gt; for the sake of interest and twisting the async feature for fun.&lt;/p&gt;  &lt;h3&gt;Round-robin independent coroutines&lt;/h3&gt;  &lt;p&gt;Our first implementation of coroutines is relatively simple. A &lt;em&gt;coordinator&lt;/em&gt; effectively &amp;quot;schedules&amp;quot; the coroutines it&amp;#39;s set up with in a round-robin fashion: when one of the coroutines yields control to the coordinator, the coordinator remembers where the coroutine had got to, and then starts the next one. When each coroutine has executed its first piece of code and yielded control, the coordinator will go back to the first coroutine to continue execution, and so on until all coroutines have completed.&lt;/p&gt;  &lt;p&gt;The coroutines don&amp;#39;t know about each other, and no data is being passed between them.&lt;/p&gt;  &lt;p&gt;Hopefully it&amp;#39;s reasonably obvious that the coordinator contains all the smarts here - the coroutines themselves can be relatively dumb. Let&amp;#39;s look at what the client code looks like (along with the results) before we get to the coordinator code.&lt;/p&gt;  &lt;h3&gt;Client code&lt;/h3&gt;  &lt;p&gt;The sample code contains three coroutines, all of which take a Coordinator parameter and have a void return type. These are passed to a new coordinator using a collection initializer and method group conversions; the coordinator is then started. Here&amp;#39;s the entry point code for this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main(&lt;span class="ReferenceType"&gt;string&lt;/span&gt;[] args)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;var&lt;/span&gt; coordinator = &lt;span class="Keyword"&gt;new&lt;/span&gt; Coordinator {&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; FirstCoroutine,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; SecondCoroutine,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ThirdCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; };     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; coordinator.Start();     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;When each coroutine is initially started, the coordinator passes a reference to &lt;em&gt;itself&lt;/em&gt; as the argument to the coroutine. That&amp;#39;s how we solve the chicken-and-egg problem of the coroutine and coordinator having to know about each other. The way a coroutine yields control is simply by awaiting the coordinator. The result type of this await expression is void - it&amp;#39;s just a way of &amp;quot;pausing&amp;quot; the coroutine.&lt;/p&gt;  &lt;p&gt;We&amp;#39;re not doing anything interesting in the actual coroutines - just tracing the execution flow. Of course we &lt;em&gt;could&lt;/em&gt; do anything we wanted, within reason. We could even await a &lt;em&gt;genuinely&lt;/em&gt; asynchronous task such as fetching a web page asynchronously. In that case the whole coroutine collection would be &amp;quot;paused&amp;quot; until the fetch returned.&lt;/p&gt;  &lt;p&gt;Here&amp;#39;s the code for the first coroutine - the second and third ones are similar, but use different indentation for clarity. The third coroutine is also shorter, just for fun - it only awaits the coordinator once.&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;async&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; FirstCoroutine(Coordinator coordinator)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Starting FirstCoroutine&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Yielding from FirstCoroutine...&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;await&lt;/span&gt; coordinator;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Returned to FirstCoroutine&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Yielding from FirstCoroutine again...&amp;quot;&lt;/span&gt;);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;await&lt;/span&gt; coordinator;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Returned to FirstCoroutine again&amp;quot;&lt;/span&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Finished FirstCoroutine&amp;quot;&lt;/span&gt;);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;And here&amp;#39;s the output...&lt;/p&gt;  &lt;div class="code"&gt;Starting FirstCoroutine    &lt;br /&gt;Yielding from FirstCoroutine...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Starting SecondCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Yielding from SecondCoroutine...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Starting ThirdCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Yielding from ThirdCoroutine...     &lt;br /&gt;Returned to FirstCoroutine     &lt;br /&gt;Yielding from FirstCoroutine again...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Returned to SecondCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Yielding from SecondCoroutine again...     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Returned to ThirdCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Finished ThirdCoroutine...     &lt;br /&gt;Returned to FirstCoroutine again     &lt;br /&gt;Finished FirstCoroutine     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Returned to SecondCoroutine again     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Finished SecondCoroutine &lt;/div&gt;  &lt;p&gt;Hopefully that&amp;#39;s the output you expected, given the earlier description. Again it may help if you think of the coroutines as running in separate pseudo-threads: the execution within each pseudo-thread is just linear, and the timing is controlled by our explicit &amp;quot;await&amp;quot; expressions. All of this would actually be pretty easy to implement using multiple threads which really &lt;em&gt;did&lt;/em&gt; just block on each await expression - but the fun part is keeping it all in one real thread. Let&amp;#39;s have a look at the coordinator.&lt;/p&gt;  &lt;h3&gt;The Coordinator class&lt;/h3&gt;  &lt;p&gt;Some of the later coroutine examples end up being slightly brainbusting, at least for me. This one is relatively straightforward though, once you&amp;#39;ve got the basic idea. All we need is a &lt;em&gt;queue&lt;/em&gt; of actions to execute. After initialization, we want our queue to contain the coroutine starting points.&lt;/p&gt;  &lt;p&gt;When a coroutine yields control, we just need to add the remainder of it to the end of the queue, and move on to the next item. Obviously the async infrastructure will provide &amp;quot;the remainder of the coroutine&amp;quot; as a continuation via the OnContinue method.&lt;/p&gt;  &lt;p&gt;When a coroutine just returns, we continue with the next item in the queue as before - it&amp;#39;s just that we won&amp;#39;t add a continuation to the end of the queue. Eventually (well, hopefully) we&amp;#39;ll end up with an empty queue, at which point we can stop.&lt;/p&gt;  &lt;h3&gt;Initialization and a choice of data structures&lt;/h3&gt;  &lt;p&gt;We&amp;#39;ll represent our queue using Queue&amp;lt;T&amp;gt; where the T is a delegate type. We have two choices here though, because we have two kinds of delegate - one which takes the Coordinator as a parameter (for the initial coroutine setup) and one which has no parameters (for the continuations). Fortunately we can convert between the two in either direction very simply, bearing in mind that all of this is within the context of a coordinator. For example:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// If we&amp;#39;re given a coroutine and want a plain Action &lt;/span&gt;    &lt;br /&gt;Action&amp;lt;Coordinator&amp;gt; coroutine = ...;&amp;#160; &lt;br /&gt;Action action = () =&amp;gt; coroutine(&lt;span class="Keyword"&gt;this&lt;/span&gt;);    &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// If we&amp;#39;re given a plain Action and want an Action&amp;lt;Continuation&amp;gt;: &lt;/span&gt;    &lt;br /&gt;Action continuation = ...;&amp;#160; &lt;br /&gt;Action&amp;lt;Coordinator&amp;gt; coroutine = ignored =&amp;gt; continuation(); &lt;/div&gt;  &lt;p&gt;I&amp;#39;ve arbitrarily chosen to use the first option, so there&amp;#39;s a Queue&amp;lt;Action&amp;gt; internally.&lt;/p&gt;  &lt;p&gt;Now we need to get the collection initializer working. The C# compiler requires an appropriate Add method (which is easy) and also checks that the type implements IEnumerable. We don&amp;#39;t really need to be able to iterate over the queue of actions, so I&amp;#39;ve use explicit interface implementation to reduce the likelihood of GetEnumerator() being called inappropriately, and made the method throw an exception for good measure. That gives us the skeleton of the class required for setting up:&lt;/p&gt;  &lt;div class="code"&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; Coordinator : IEnumerable    &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; Queue&amp;lt;Action&amp;gt; actions = &lt;span class="Keyword"&gt;new&lt;/span&gt; Queue&amp;lt;Action&amp;gt;();    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Used by collection initializer to specify the coroutines to run&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Add(Action&amp;lt;Coordinator&amp;gt; coroutine)    &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; actions.Enqueue(() =&amp;gt; coroutine(&lt;span class="Keyword"&gt;this&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="InlineComment"&gt;// Required for collection initializers, but we don&amp;#39;t really want&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// to expose anything.&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; IEnumerator IEnumerable.GetEnumerator()    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; NotSupportedException(&lt;span class="String"&gt;&amp;quot;IEnumerable only supported to enable collection initializers&amp;quot;&lt;/span&gt;);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;(Note that I haven&amp;#39;t used XML documentation anywhere here - it&amp;#39;s great for real code, but adds clutter in blog posts.)&lt;/p&gt;  &lt;p&gt;For production code I&amp;#39;d probably prevent Add from being called after the coordinator had been started, but there&amp;#39;s no need to do it in our well-behaved sample code. We&amp;#39;re only going to add extra actions to the queue via continuations, which will be added due to await expressions.&lt;/p&gt;  &lt;h3&gt;The main execution loop and async infrastructure&lt;/h3&gt;  &lt;p&gt;So far we&amp;#39;ve got code to register coroutines in the queue - so now we need to execute them. Bearing in mind that the actions themselves will be responsible for adding continuations, the main loop of the coordinator is embarrassingly simple:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Execute actions in the queue until it&amp;#39;s empty. Actions add *more*&lt;/span&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// actions (continuations) to the queue by awaiting this coordinator.&lt;/span&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Start()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;while&lt;/span&gt; (actions.Count &amp;gt; 0)    &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; actions.Dequeue().Invoke();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Of course, the interesting bit is the code which supports the async methods and await expressions. We know we need to provide a GetAwaiter() method, but what should that return? Well, we&amp;#39;re just going to use the awaiter to add a continuation to the coordinator&amp;#39;s queue. It&amp;#39;s got no other state than that - so we might as well return the coordinator itself, and put the other infrastructure methods directly in the coordinator.&lt;/p&gt;  &lt;p&gt;Again, this is &lt;em&gt;slightly&lt;/em&gt; ugly, as the extra methods don&amp;#39;t really make sense on the coordinator - we wouldn&amp;#39;t want to call them directly from client code, for example. However, they&amp;#39;re fairly irrelevant - we could always create a nested type which just had a reference to its &amp;quot;parent&amp;quot; coordinator if we wanted to. For simplicity, I haven&amp;#39;t bothered with this - I&amp;#39;ve just implemented GetAwaiter() trivially:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Used by await expressions to get an awaiter&lt;/span&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt; Coordinator GetAwaiter()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;this&lt;/span&gt;;    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;So, that leaves just three members still to implement: IsCompleted, OnCompleted and GetResult. We always want the IsCompleted property to return false, as otherwise the coroutine will just continue executing &lt;em&gt;immediately&lt;/em&gt; without returning to cede control; the await expression would be pointless. OnCompleted &lt;em&gt;just&lt;/em&gt; needs to add the continuation to the end of the queue - we don&amp;#39;t need to attach it to a task, or anything like that. Finally, GetResult is a no-op - we have no results, no exceptions, and basically nothing to do. You might want to add a bit of logging here, if you were so inclined, but there&amp;#39;s no real need.&lt;/p&gt;  &lt;p&gt;So, here are the final three members of Coordinator:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="InlineComment"&gt;// Force await to yield control&lt;/span&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;bool&lt;/span&gt; IsCompleted { get { &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;false&lt;/span&gt;; } }    &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; OnCompleted(Action continuation)    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Put the continuation at the end of the queue, ready to&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// execute when the other coroutines have had a go.&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; actions.Enqueue(continuation);    &lt;br /&gt;}    &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; GetResult()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Our await expressions are void, and we never need to throw&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// an exception, so this is a no-op.&lt;/span&gt;    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;And that&amp;#39;s it! Fewer than 50 lines of code required, and nothing complicated at all. The interesting behaviour is all due to the way the C# compiler &lt;em&gt;uses&lt;/em&gt; the coordinator when awaiting it.&lt;/p&gt;  &lt;p&gt;We need AsyncVoidMethodBuilder as before, as we have some async void methods - but that doesn&amp;#39;t need to do anything significant. That&amp;#39;s basically all the code required to implement these basic round-robin coroutines.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;Our first foray into the weird and wonderful world of coroutines was relatively tame. The basic idea of a coordinator keeping track of the state of all the different coroutines in one sense or another will keep coming back to us, but with different ways of controlling the execution flow.&lt;/p&gt;  &lt;p&gt;Next time we&amp;#39;ll see some coroutines which can pass data to each other.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1795089" 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/C_2300_+5/default.aspx">C# 5</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/async/default.aspx">async</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx">Eduasync</category></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>The curious case of the publicity-seeking interface and the shy abstract class</title><link>http://msmvps.com/blogs/jon_skeet/archive/2010/10/03/the-curious-case-of-the-publicity-seeking-interface-and-the-shy-abstract-class.aspx</link><pubDate>Sun, 03 Oct 2010 19:05:58 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1779234</guid><dc:creator>skeet</dc:creator><slash:comments>26</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1779234</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1779234</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2010/10/03/the-curious-case-of-the-publicity-seeking-interface-and-the-shy-abstract-class.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://noda-time.googlecode.com"&gt;Noda Time&lt;/a&gt; has a guilty secret, and I&amp;#39;m not just talking about the fact that there&amp;#39;s been very little progress on it recently. (It&amp;#39;s not dead as a project - I have high hopes, when I can put some quality time into it.) This secret is called &lt;code&gt;LocalInstant&lt;/code&gt;, and it&amp;#39;s a pain in the neck.&lt;/p&gt;  &lt;p&gt;One of the nice things about giving talks about an API you&amp;#39;re currently writing is that you can see which concepts make sense to people, and which don&amp;#39;t - as well as seeing which concepts you&amp;#39;re able to explain and which you can&amp;#39;t. &lt;code&gt;LocalInstant&lt;/code&gt; has been an awkward type to explain right from day 1, and I don&amp;#39;t think it&amp;#39;s improved much since then. For the purpose of this blog post, you don&amp;#39;t actually need to know what it means, but if you&amp;#39;re really interested, imagine that it&amp;#39;s like a time-zone-less date and time (such as &amp;quot;10:58 on July 2nd 2015&amp;quot; but also missing a calendar system, so you can&amp;#39;t really tell what the month is etc. The important point is that it&amp;#39;s not just time-zone-less, but it&amp;#39;s actually &lt;em&gt;local&lt;/em&gt; - so it doesn&amp;#39;t represent a single instant in time. Unlike every other concept in Noda Time, I haven&amp;#39;t thought of any good analogy between &lt;code&gt;LocalInstant&lt;/code&gt; and the real world.&lt;/p&gt;  &lt;p&gt;Now, I don&amp;#39;t like having types I can&amp;#39;t describe easily, and I&amp;#39;d &lt;em&gt;love&lt;/em&gt; to just get rid of it completely... but it&amp;#39;s actually an incredibly powerful concept to have in the library. Not for &lt;em&gt;users&lt;/em&gt; of course, but for the &lt;em&gt;implementation&lt;/em&gt;. It&amp;#39;s spattered all over the place. Okay, the next best step to removing it is to hide it away from consumers: let&amp;#39;s make it internal. Unfortunately, that doesn&amp;#39;t work either, because it&amp;#39;s referred to in interfaces all the time too. For example, almost &lt;em&gt;every&lt;/em&gt; member of &lt;code&gt;ICalendarSystem&lt;/code&gt; has &lt;code&gt;LocalInstant&lt;/code&gt; as one of its parameters.&lt;/p&gt;  &lt;h3&gt;The rules around interfaces&lt;/h3&gt;  &lt;p&gt;Just to recap, every member of an interface - even an internal interface - is implicitly public. That causes some interesting restrictions. Firstly, every type referred to in a public interface must be public. So this would be invalid:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;struct&lt;/span&gt; LocalInstant {}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Doesn&amp;#39;t compile: Inconsistent accessibility&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; ICalendarSystem     &lt;br /&gt;{&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; LocalInstant GetLocalInstant(&lt;span class="ValueType"&gt;int&lt;/span&gt; year, &lt;span class="ValueType"&gt;int&lt;/span&gt; month, &lt;span class="ValueType"&gt;int&lt;/span&gt; day);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;So far, so good. It&amp;#39;s entirely reasonable that a public member&amp;#39;s declaration shouldn&amp;#39;t refer to an internal type. Calling code wouldn&amp;#39;t understand what &lt;code&gt;LocalInstant&lt;/code&gt; was, so how could it possibly use &lt;code&gt;ICalendarSystem&lt;/code&gt; sensibly? But suppose we only wanted to declare the interface internally. That should be okay, right? Indeed, the compiler allows the following code:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;struct&lt;/span&gt; LocalInstant {}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Compiles with no problems&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; ICalendarSystem     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; LocalInstant GetLocalInstant(&lt;span class="ValueType"&gt;int&lt;/span&gt; year, &lt;span class="ValueType"&gt;int&lt;/span&gt; month, &lt;span class="ValueType"&gt;int&lt;/span&gt; day);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;But hang on... isn&amp;#39;t &lt;code&gt;GetLocalInstant&lt;/code&gt; public? That&amp;#39;s what I said earlier, right? So we&amp;#39;re declaring a public member using an internal type... which we thought wasn&amp;#39;t allowed. Is this a compiler bug?&lt;/p&gt;  &lt;p&gt;Well, no. My earlier claim that &amp;quot;a public member&amp;#39;s declaration shouldn&amp;#39;t refer to an internal type&amp;quot; isn&amp;#39;t nearly precise enough. The important aspect isn&amp;#39;t just whether the member is declared public - but its &lt;em&gt;accessibility domain&lt;/em&gt;. In this case, the accessibility domain of &lt;code&gt;ICalendarSystem.GetLocalInstant&lt;/code&gt; is only the assembly, which is why it&amp;#39;s a valid declaration.&lt;/p&gt;  &lt;p&gt;However, life becomes fun when we try to &lt;em&gt;implement&lt;/em&gt; &lt;code&gt;ICalendarSystem&lt;/code&gt; in a public class. It&amp;#39;s perfectly valid for a public class to implement an internal interface, but we have some problems declaring the method implementing &lt;code&gt;GetLocalInstant&lt;/code&gt;. We can&amp;#39;t make it a public method, because at that point its accessibility domain would be anything referring to the assembly, but the accessibility domain of &lt;code&gt;LocalInstant&lt;/code&gt; itself would still only be the assembly. We can&amp;#39;t make it internal, because it&amp;#39;s implementing an interface member, which is public.&lt;/p&gt;  &lt;p&gt;There &lt;em&gt;is&lt;/em&gt; an alternative though: explicit interface implementation. That comes with all kinds of other interesting points, but it does at least compile:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;struct&lt;/span&gt; LocalInstant {}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; ICalendarSystem     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; LocalInstant GetLocalInstant(&lt;span class="ValueType"&gt;int&lt;/span&gt; year, &lt;span class="ValueType"&gt;int&lt;/span&gt; month, &lt;span class="ValueType"&gt;int&lt;/span&gt; day);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; GregorianCalendarSystem : ICalendarSystem     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Has to be implemented explicitly&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; LocalInstant ICalendarSystem.GetLocalInstant(&lt;span class="ValueType"&gt;int&lt;/span&gt; year, &lt;span class="ValueType"&gt;int&lt;/span&gt; month, &lt;span class="ValueType"&gt;int&lt;/span&gt; day);     &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;// Implementation &lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;}&lt;/div&gt;  &lt;p&gt;So, we&amp;#39;ve got &lt;em&gt;somewhere&lt;/em&gt; at this point. We&amp;#39;ve managed to make a type used within an interface internal, but at the cost of making the interface itself internal, and requiring explicit interface implementation within any public classes implementing the interface.&lt;/p&gt;  &lt;p&gt;That could potentially be useful in Noda Time, but it doesn&amp;#39;t solve our real &lt;code&gt;LocalInstant&lt;/code&gt; / &lt;code&gt;ICalendarSystem&lt;/code&gt; problem. We need &lt;code&gt;ICalendarSystem&lt;/code&gt; to be public, because consumers need to be able to specify a calendar when they create an instance of &lt;code&gt;ZonedDateTime&lt;/code&gt; or something similar. Interfaces are just too demanding in terms of publicity.&lt;/p&gt;  &lt;p&gt;Fortunately, we have another option up our sleeves...&lt;/p&gt;  &lt;h3&gt;Abstract classes to the rescue!&lt;/h3&gt;  &lt;p&gt;I should come clean at this point and say that generally speaking, I&amp;#39;m an interface weenie. Whenever I need a reusable and testable abstraction, I reach for interfaces by default. I have a general bias against concrete inheritance, including abstract classes. I&amp;#39;m probably a little too harsh on them though... particularly as in this case they do everything I need them to.&lt;/p&gt;  &lt;p&gt;In Noda Time, I definitely &lt;em&gt;don&amp;#39;t&lt;/em&gt; need the ability to implement ICalendarSystem and derive from another concrete class... so making it a purely abstract class will be okay in those terms. Let&amp;#39;s see what happens when we try:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; LocalInstant {}&amp;#160; &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;abstract&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; CalendarSystem     &lt;br /&gt;{&amp;#160; &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;abstract&lt;/span&gt; LocalInstant GetLocalInstant(&lt;span class="ValueType"&gt;int&lt;/span&gt; year, &lt;span class="ValueType"&gt;int&lt;/span&gt; month, &lt;span class="ValueType"&gt;int&lt;/span&gt; day);     &lt;br /&gt;}&amp;#160; &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; GregorianCalendarSystem : CalendarSystem     &lt;br /&gt;{&amp;#160;&amp;#160; &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;override&lt;/span&gt; LocalInstant GetLocalInstant(&lt;span class="ValueType"&gt;int&lt;/span&gt; year, &lt;span class="ValueType"&gt;int&lt;/span&gt; month, &lt;span class="ValueType"&gt;int&lt;/span&gt; day)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Implementation&lt;/span&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&amp;#160; &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Hoorah! Now we&amp;#39;ve hidden away &lt;code&gt;LocalInstant&lt;/code&gt; but left &lt;code&gt;CalendarSystem&lt;/code&gt; public, just as we wanted to. We could make &lt;code&gt;GregorianCalendarSystem&lt;/code&gt; public or not, as we felt like it. If we want to make any of &lt;code&gt;CalendarSystem&lt;/code&gt;&amp;#39;s abstract methods public, then we can do so provided they don&amp;#39;t require any internal types. There&amp;#39;s on interesting point though: types outside the assembly can&amp;#39;t derive from &lt;code&gt;CalendarSystem&lt;/code&gt;. It&amp;#39;s a little bit as if the class only provided an internal constructor, but with a little bit more of an air of mystery... you can override every method you can actually &lt;em&gt;see&lt;/em&gt;, and still get a compile-time error message like this:&lt;/p&gt;  &lt;div class="code"&gt;OutsideCalendar.cs(1,14): error CS0534: &amp;#39;OutsideCalendar&amp;#39; does not implement inherited abstract member   &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;#39;CalendarSystem.GetLocalInstant(int, int, int)&amp;#39; &lt;/div&gt;  &lt;p&gt;I can just imagine the author of the other assembly thinking, &amp;quot;But I can&amp;#39;t even &lt;em&gt;see&lt;/em&gt; that method! What is it? Where is it coming from?&amp;quot; Certainly a case where the documentation needs to be clear. Whereas it&amp;#39;s impossible to create an interface which is &lt;em&gt;visible&lt;/em&gt; to the outside world but can&amp;#39;t be &lt;em&gt;implemented&lt;/em&gt; externally, that&amp;#39;s precisely the situation we&amp;#39;ve reached here.&lt;/p&gt;  &lt;p&gt;The abstract class is a little bit like an authentication token given by a single-sign-on system. From the outside, it&amp;#39;s an opaque item: you don&amp;#39;t know what&amp;#39;s in it or how it does its job... all you know is that you need to obtain it, and then you can use it to do other things. On the inside, it&amp;#39;s much richer - full of useful data and members.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;Until recently, I hadn&amp;#39;t thought of using abstract classes like this. It would possibly be nice if we &lt;em&gt;could&lt;/em&gt; use interfaces in the same way, effectively limiting the implementation to be in the declaring assembly, but letting the interface itself (and some members) be visible externally.&lt;/p&gt;  &lt;p&gt;A bigger question is whether this is a good idea in terms of design anyway. If I &lt;em&gt;do&lt;/em&gt; make &lt;code&gt;LocalInstant&lt;/code&gt; internal, there will be a lot of interfaces which go the same way... or become completely internal. For example, the whole &amp;quot;fields&amp;quot; API of Noda Time could become an implementation detail, with suitable helper methods to fetch things like &amp;quot;how many days are there in the given month.&amp;quot; The fields API is an elegant overall design, but it&amp;#39;s quite complicated considering the very limited situations in which most callers will use it.&lt;/p&gt;  &lt;p&gt;I suspect I will try to go for this &amp;quot;reduced API&amp;quot; for v1, knowing that we can always make things more public later on... that way we give ourselves a bit more flexibility in terms of not having to get everything right first time within those APIs, too.&lt;/p&gt;  &lt;p&gt;Part of me still feels uncomfortable with the level of hiding involved - I know other developers I respect deeply who hide as little as possible, for maximum flexibility - but I &lt;em&gt;do&lt;/em&gt; like the idea of an API which is really simple to browse.&lt;/p&gt;  &lt;p&gt;Aside from the concrete use case of Noda Time, this has proved an interesting exercise in terms of revisiting accessibility and the rules on what C# allows.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1779234" 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/Noda+Time/default.aspx">Noda Time</category></item><item><title>Non-iterable collection initializers</title><link>http://msmvps.com/blogs/jon_skeet/archive/2010/09/18/non-iterable-collection-initializers.aspx</link><pubDate>Sat, 18 Sep 2010 07:48:19 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1778282</guid><dc:creator>skeet</dc:creator><slash:comments>15</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1778282</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1778282</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2010/09/18/non-iterable-collection-initializers.aspx#comments</comments><description>&lt;p&gt;Yesterday on Stack Overflow, I mentioned that sometimes I make a type implement IEnumerable just so that I can use collection initializers with it. In such a situation, I use explicit interface implementation (despite not really &lt;em&gt;needing&lt;/em&gt; to - I&amp;#39;m not implementing IEnumerable&amp;lt;T&amp;gt;) and leave it throwing a NotImplementedException. (EDIT: As noted in the comments, throwing NotSupportedException would probably be more appropriate. In many cases it would actually be pretty easy to implement this in &lt;em&gt;some&lt;/em&gt; sort of meaningful fashion... although I quite like throwing an exception to indicate that it&amp;#39;s not really &lt;em&gt;intended&lt;/em&gt; to be treated as a sequence.)&lt;/p&gt;  &lt;p&gt;Why would I do such a crazy thing? Because sometimes it&amp;#39;s helpful to be able to construct a &amp;quot;collection&amp;quot; of items easily, even if you only want the class itself to really treat it as a collection. As an example, in a benchmarking system you might want to be able to add a load of tests individually, but you never want to ask the &amp;quot;test collection&amp;quot; what tests are in it... you just want to &lt;em&gt;run&lt;/em&gt; the tests. The only iteration is done internally.&lt;/p&gt;  &lt;p&gt;Now, there&amp;#39;s an alternative to collection initializers here: parameter arrays. You can add a &amp;quot;params string[]&amp;quot; or whatever as the final constructor parameter, and simply use the constructor. That works fine in many cases, but it falls down in others:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;If you want to be able to add different types of values, without just using &amp;quot;params object[]&amp;quot;. For example, suppose we wanted to restrict our values to int, string, DateTime and Guid... you can&amp;#39;t do that in a compile-time-safe way using a parameter array. &lt;/li&gt;    &lt;li&gt;If you want to be able to constructor composite values from two or more parts, without having to explicitly construct that composite value each time. Think about the difference in readability between using a collection initializer for a dictionary and explicitly constructing a KeyValuePair&amp;lt;TKey, TValue&amp;gt; for each entry. &lt;/li&gt;    &lt;li&gt;If you want to be able to use generics to force aspects of type safety. The Add method can be generic, so you could, for example, force two parameters for a single entry to both be of T, but different entries could have different types. This is pretty unusual, but I needed it just the other day :) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now, it&amp;#39;s a bit of a hack to have to &amp;quot;not quite implement&amp;quot; IEnumerable. I&amp;#39;ve come up with two alternative options. These have the additional benefit of not requiring the method to always be called Add any more. I suspect it still would be in most cases, but flexibility is a bonus.&lt;/p&gt;  &lt;h3&gt;Option 1: Class level attribute&lt;/h3&gt;  &lt;p&gt;Instead of just relying on IEnumerable, the compiler could detect an attribute applied to the class, specifying the single method name for all collection initializer methods:&lt;/p&gt;  &lt;div class="code"&gt;[CollectionInitializerMethod(&lt;span class="String"&gt;&amp;quot;AddValue&amp;quot;&lt;/span&gt;)]     &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; RestrictedValues     &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;void&lt;/span&gt; AddValue(&lt;span class="ValueType"&gt;int&lt;/span&gt; x) { ... }     &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;void&lt;/span&gt; AddValue(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; y) { ... }     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; values = &lt;span class="Keyword"&gt;new&lt;/span&gt; RestrictedValues     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; 3, &lt;span class="String"&gt;&amp;quot;value&amp;quot;&lt;/span&gt;, 10     &lt;br /&gt;}; &lt;/div&gt;  &lt;h3&gt;Option 2: Method level attributes&lt;/h3&gt;  &lt;p&gt;In this case, each method eligible for use in a collection initializer would be decorated with the attribute:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; RestrictedValues     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [CollectionInitializerMethod]     &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; AddInt32(&lt;span class="ValueType"&gt;int&lt;/span&gt; x) { ... }     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [CollectionInitializerMethod]     &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; AddString(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; y) { ... }     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; values = &lt;span class="Keyword"&gt;new&lt;/span&gt; RestrictedValues     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; 3, &lt;span class="String"&gt;&amp;quot;value&amp;quot;&lt;/span&gt;, 10     &lt;br /&gt;}; &lt;/div&gt;  &lt;p&gt;This has the disadvantage that the compiler would need to look at every method in the target class when it found a collection initializer.&lt;/p&gt;  &lt;p&gt;Obviously both of these can be made backwardly compatible very easily: the presence of an implementation of IEnumerable with no attributes present would just fall back to using Add.&lt;/p&gt;  &lt;h3&gt;Option 3: Compiler and language simplicity&lt;/h3&gt;  &lt;p&gt;(I&amp;#39;ve added this in response to Peter&amp;#39;s comment.)&lt;/p&gt;  &lt;p&gt;Okay, let&amp;#39;s stick with the Add method. All we need is another way of indicating that you should be able to use collection initializers with a type:&lt;/p&gt;  &lt;div class="code"&gt;[AllowCollectionInitializers]&amp;#160; &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; RestrictedValues&amp;#160; &lt;br /&gt;{&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Add(&lt;span class="ValueType"&gt;int&lt;/span&gt; x) { ... }&amp;#160; &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;void&lt;/span&gt; Add(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; y) { ... }&amp;#160; &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;At this point, the changes required to the compiler (and language spec) are really minimal. In the bit of code which detects whether or not you can use a collection initializer, you just need to change from &amp;quot;does this type implement IEnumerable&amp;quot; to &amp;quot;does this type implement IEnumerable or have the relevant attribute defined&amp;quot;. I can&amp;#39;t think of many possible language changes which would be more localized than that.&lt;/p&gt;  &lt;h3&gt;And another thing...&lt;/h3&gt;  &lt;p&gt;One final point. I&amp;#39;d still like the ability for collection initializers to return a value, and for that value to be used for subsequent elements of the initialization - with the final return value being the last-returned value. Any methods with a void return value would be treated as if they returned &amp;quot;this&amp;quot;. This would allow you to build immutable collections easily.&lt;/p&gt;  &lt;p&gt;Likewise you could decorate methods with a [PropertyInitializerMethod] to allow initialization of immutable types with &amp;quot;WithXyz&amp;quot; methods. Admittedly there&amp;#39;s less need for this now that we have optional parameters and named arguments in C# 4 - a lot of the benefits of object initializers are available just with constructors.&lt;/p&gt;  &lt;p&gt;Anyway, just a few slightly odd thoughts around initialization for you to ponder over the weekend...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1778282" 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></item><item><title>Iterate, damn you!</title><link>http://msmvps.com/blogs/jon_skeet/archive/2010/07/27/iterate-damn-you.aspx</link><pubDate>Tue, 27 Jul 2010 18:52:23 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1774820</guid><dc:creator>skeet</dc:creator><slash:comments>15</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1774820</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1774820</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2010/07/27/iterate-damn-you.aspx#comments</comments><description>&lt;p&gt;Do you know the hardest thing about presenting code with surprising results? It&amp;#39;s hard to do so without effectively inviting readers to look for the trick. Not that that&amp;#39;s always enough - I failed the last of &lt;a href="http://blogs.msdn.com/b/ericlippert/archive/2010/07/08/spoiler-alert.aspx"&gt;Neal and Eric&amp;#39;s C# puzzlers&lt;/a&gt; at NDC, for example. (If you haven&amp;#39;t already watched the video, please do so now. It&amp;#39;s far more entertaining than this blog post.) Anyway, this one may be obvious to some of you, but there are some interesting aspects even when you&amp;#39;ve got the twist, as it were.&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; System;     &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Collections.Generic;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; WeirdIterators     &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; ShowNext(IEnumerator&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; iterator)     &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; (iterator.MoveNext())     &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(iterator.Current);     &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;else&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;Done&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; }     &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; List&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; values = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; { 1, 2 };     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Namespace"&gt;using&lt;/span&gt; (&lt;span class="Linq"&gt;var&lt;/span&gt; iterator = values.GetEnumerator())     &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; ShowNext(iterator);     &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; ShowNext(iterator);     &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; ShowNext(iterator);     &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;If you guessed &amp;quot;1, 2, Done&amp;quot; despite the title of the post and the hints that it was surprising, then you&amp;#39;re at least brave and firm in your beliefs. I suspect most readers will correctly guess that it prints &amp;quot;1, 1, 1&amp;quot; - but I also suspect some of you won&amp;#39;t have worked out why.&lt;/p&gt;  &lt;p&gt;Let&amp;#39;s look at the signature of &lt;code&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/b0yss765.aspx"&gt;List&amp;lt;T&amp;gt;.GetEnumerator()&lt;/a&gt;&lt;/code&gt;. We&amp;#39;d expect it to be&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt; IEnumerator&amp;lt;T&amp;gt; GetEnumerator() &lt;/div&gt;  &lt;p&gt;right? That&amp;#39;s what &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; says it&amp;#39;ll look like. Well, no. List&amp;lt;T&amp;gt; uses explicit interface implementation for &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt;. The signature &lt;i&gt;actually&lt;/i&gt; looks like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt; List&amp;lt;T&amp;gt;.Enumerator GetEnumerator() &lt;/div&gt;  &lt;p&gt;Hmm... that&amp;#39;s an unfamiliar type. Let&amp;#39;s have another look in &lt;a href="http://msdn.microsoft.com/en-us/library/x854yt9s.aspx"&gt;MSDN&lt;/a&gt;...&lt;/p&gt;  &lt;div class="code"&gt;[SerializableAttribute]    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;struct&lt;/span&gt; Enumerator : IEnumerator&amp;lt;T&amp;gt;,&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; IDisposable, IEnumerator &lt;/div&gt;  &lt;p&gt;(It&amp;#39;s nested in &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt; of course.) Now that&amp;#39;s odd... it&amp;#39;s a struct. You don&amp;#39;t see many custom structs around, beyond the familiar ones in the &lt;code&gt;System&lt;/code&gt; namespace. And hang on, don&amp;#39;t iterators fundamentally have to be mutable.&lt;/p&gt;  &lt;p&gt;Ah. &amp;quot;Mutable value type&amp;quot; - a phrase to strike terror into the hearts of right-headed .NET developers everywhere.&lt;/p&gt;  &lt;p&gt;So what&amp;#39;s going on? If we&amp;#39;re losing all the changes to the value, why is it printing &amp;quot;1, 1, 1&amp;quot; instead of throwing an exception due to printing out &lt;code&gt;Current&lt;/code&gt; without first moving?&lt;/p&gt;  &lt;p&gt;Well, we&amp;#39;re fetching the iterator into a variable of type &lt;code&gt;List&amp;lt;int&amp;gt;.Enumerator&lt;/code&gt;, and then calling &lt;code&gt;ShowNext()&lt;/code&gt; three times. On each call, the value is boxed (creating a copy), and the reference to the box is passed to &lt;code&gt;ShowNext()&lt;/code&gt;.&lt;/p&gt;  &lt;p&gt;Within &lt;code&gt;ShowNext()&lt;/code&gt;, the value within the box changes when we call &lt;code&gt;MoveNext()&lt;/code&gt; - which is how it&amp;#39;s able to get the real first element with Current. So that mutation isn&amp;#39;t lost... until we return from the method. The box is now eligible for garbage collection, and no change has been made to the &lt;code&gt;iterator&lt;/code&gt; variable&amp;#39;s value. On the next call to &lt;code&gt;ShowNext()&lt;/code&gt;, a new box is created and we see the first item again...&lt;/p&gt;  &lt;h2&gt;How can we fix it?&lt;/h2&gt;  &lt;p&gt;There are various things we can do to fix the code - or at least, to make it display &amp;quot;1, 2, Done&amp;quot;. We can then find other ways of breaking it again :)&lt;/p&gt;  &lt;h3&gt;Change the type of the &lt;code&gt;values&lt;/code&gt; variable&lt;/h3&gt;  &lt;p&gt;How does the compiler work out the type of the &lt;code&gt;iterator&lt;/code&gt; variable? Why, it looks at the return type of &lt;code&gt;values.GetEnumerator()&lt;/code&gt;. And how does it find that? It looks at the type of the &lt;code&gt;values&lt;/code&gt; variable, and then finds the &lt;code&gt;GetEnumerator()&lt;/code&gt; method. In this case it finds &lt;code&gt;List&amp;lt;int&amp;gt;.GetEnumerator()&lt;/code&gt;, so it makes the &lt;code&gt;iterator&lt;/code&gt; variable type &lt;code&gt;List&amp;lt;int&amp;gt;.Enumerator&lt;/code&gt;.&lt;/p&gt;  &lt;p&gt;If suppose just change &lt;code&gt;values&lt;/code&gt; to be of type &lt;code&gt;IList&amp;lt;int&amp;gt;&lt;/code&gt; (or &lt;code&gt;IEnumerable&amp;lt;int&amp;gt;&lt;/code&gt;, or &lt;code&gt;ICollection&amp;lt;int&amp;gt;&lt;/code&gt;):&lt;/p&gt;  &lt;div class="code"&gt;IList&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; values = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; { 1, 2 }; &lt;/div&gt;  &lt;p&gt;The compiler uses the interface implementation of &lt;code&gt;GetEnumerator()&lt;/code&gt; on List&amp;lt;T&amp;gt;. Now that &lt;em&gt;could&lt;/em&gt; return a different type entirely - but it actually returns a boxed &lt;code&gt;List&amp;lt;T&amp;gt;.Enumerator&lt;/code&gt;. We can see that by just printing out &lt;code&gt;iterator.GetType()&lt;/code&gt;.&lt;/p&gt;  &lt;p&gt;So if it&amp;#39;s just returning the same value as before, why does it work?&lt;/p&gt;  &lt;p&gt;Well, this time we&amp;#39;re boxing &lt;em&gt;once - &lt;/em&gt;the iterator gets boxed on its way out of the &lt;code&gt;GetEnumerator()&lt;/code&gt; method, and the same box is used for all three calls to &lt;code&gt;ShowNext()&lt;/code&gt;. No extra copies are created, and the changes within the box don&amp;#39;t get lost.&lt;/p&gt;  &lt;h3&gt;Change the type of the &lt;code&gt;iterator&lt;/code&gt; variable&lt;/h3&gt;  &lt;p&gt;This is exactly the same as the previous fix - except we don&amp;#39;t need to change the type of &lt;code&gt;values&lt;/code&gt;. We can just explicitly state the type of &lt;code&gt;iterator&lt;/code&gt;:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; (IEnumerator&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; iterator = values.GetEnumerator()) &lt;/div&gt;  &lt;p&gt;The reason this works is the same as before - we box once, and the changes within the box don&amp;#39;t get lost.&lt;/p&gt;  &lt;h3&gt;Pass the &lt;code&gt;iterator&lt;/code&gt; variable by reference&lt;/h3&gt;  &lt;p&gt;The initial problem was due to the mutations involved in &lt;code&gt;ShowNext()&lt;/code&gt; getting lost due to repeated boxing. We&amp;#39;ve seen how to solve it by reducing the number of boxing operations down to one, but can we remove them entirely?&lt;/p&gt;  &lt;p&gt;Well yes, we can. If we want changes to the value of the parameter in &lt;code&gt;ShowNext()&lt;/code&gt; to be propagated back to the caller, we just need to pass the variable by reference. When passing by reference the parameter and argument types have to match exactly of course, so we can&amp;#39;t leave the &lt;code&gt;iterator&lt;/code&gt; variable being type &lt;code&gt;List&amp;lt;T&amp;gt;.Enumerator&lt;/code&gt; without changing the parameter type. Now we &lt;em&gt;could&lt;/em&gt; explicitly change the type of the parameter to &lt;code&gt;List&amp;lt;T&amp;gt;.Enumerator&lt;/code&gt; - but that would tie our implementation down rather a lot, wouldn&amp;#39;t it? Let&amp;#39;s use generics instead:&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; ShowNext&amp;lt;T&amp;gt;(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; T iterator)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;where&lt;/span&gt; T : IEnumerator&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; &lt;/div&gt;  &lt;p&gt;Now we can pass &lt;code&gt;iterator&lt;/code&gt; by reference and the compiler will infer the type. The interface members (&lt;code&gt;MoveNext()&lt;/code&gt; and &lt;code&gt;Current&lt;/code&gt;) will be called using constrained calls, so there&amp;#39;s no boxing involved...&lt;/p&gt;  &lt;p&gt;... except that when you try to just change the method calls to use &lt;code&gt;ref&lt;/code&gt;, it doesn&amp;#39;t work - because apparently you can&amp;#39;t pass a &amp;quot;using variable&amp;quot; by reference. I&amp;#39;d never come across that rule before. Interesting. Fortunately, we can (roughly) expand out the &lt;code&gt;using&lt;/code&gt; statement ourselves, like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; iterator = values.GetEnumerator();     &lt;br /&gt;&lt;span class="Statement"&gt;try&lt;/span&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ShowNext(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; iterator);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ShowNext(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; iterator);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ShowNext(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; iterator);     &lt;br /&gt;}     &lt;br /&gt;&lt;span class="Statement"&gt;finally&lt;/span&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; iterator.Dispose();     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Again, this fixes the problem - and this time there&amp;#39;s no boxing involved.&lt;/p&gt;  &lt;p&gt;Let&amp;#39;s quickly look at one more example of it &lt;em&gt;not&lt;/em&gt; working, before I finish...&lt;/p&gt;  &lt;h3&gt;Dynamic typing to the anti-rescue&lt;/h3&gt;  &lt;p&gt;What happens if we change the type of &lt;code&gt;iterator&lt;/code&gt; to &lt;code&gt;dynamic&lt;/code&gt; (and set everything else back the way it was)? I&amp;#39;ll readily admit, I really didn&amp;#39;t know what was going to happen here. There are two competing forces:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The &lt;code&gt;dynamic&lt;/code&gt; type is often really just &lt;code&gt;object&lt;/code&gt; behind the scenes... so it will be boxed once, right? That means the changes within the box won&amp;#39;t get lost. (This would give &amp;quot;1, 2, Done&amp;quot;) &lt;/li&gt;    &lt;li&gt;The &lt;code&gt;dynamic&lt;/code&gt; type is in many ways meant to act as if you&amp;#39;d declared a variable of the type which it &lt;em&gt;actually &lt;/em&gt;turns out to be at execution time - so in this case it should work as if the variable was of type &lt;code&gt;List&amp;lt;int&amp;gt;.Enumerator&lt;/code&gt;, just like our original code. (This would give &amp;quot;1, 1, 1&amp;quot;) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;What actually happens? I believe it actually boxes the value returned from &lt;code&gt;GetEnumerator()&lt;/code&gt; - and then the C# binder &lt;strike&gt;DLR&lt;/strike&gt; makes sure that the value type behaviour is preserved by &lt;em&gt;copying the box&lt;/em&gt; before passing it to &lt;code&gt;ShowNext()&lt;/code&gt;. In other words, both bits of intuition are right, but the second effectively overrules the first. Wow. (See the comment below from Chris Burrows for more information about this. I&amp;#39;m sure he&amp;#39;s right that it&amp;#39;s the only design that makes sense. This is a pretty pathological example in various ways.)&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;Just say &amp;quot;no&amp;quot; to mutable value types. They do weird things.&lt;/p&gt;  &lt;p&gt;(Fortunately the vast majority of the time this particular one won&amp;#39;t be a problem - it&amp;#39;s rare to use iterators explicitly in the first place, and when you do you &lt;em&gt;very&lt;/em&gt; rarely pass them to another method.)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1774820" 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></item><item><title>First encounters with Reactive Extensions</title><link>http://msmvps.com/blogs/jon_skeet/archive/2010/01/16/first-encounters-with-reactive-extensions.aspx</link><pubDate>Sat, 16 Jan 2010 20:13:42 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1752014</guid><dc:creator>skeet</dc:creator><slash:comments>15</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1752014</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1752014</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2010/01/16/first-encounters-with-reactive-extensions.aspx#comments</comments><description>&lt;p&gt;I&amp;#39;ve been researching &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;Reactive Extensions&lt;/a&gt; for the last few days, with an eye to writing a short section in chapter 12 of the second edition of C# in Depth. (This is the most radically changed chapter from the first edition; it will be covering LINQ to SQL, IQueryable, LINQ to XML, Parallel LINQ, Reactive Extensions, and writing your own LINQ to Objects operators.) I&amp;#39;ve watched various videos from &lt;a href="http://channel9.msdn.com/tags/Rx/"&gt;Channel 9&lt;/a&gt;, but today was the first time I actually played with it. I&amp;#39;m half excited, and half disappointed.&lt;/p&gt;  &lt;p&gt;My excited half sees that there&amp;#39;s an awful lot to experiment with, and loads to learn about join patterns etc. I&amp;#39;m also looking forward to trying genuine events (mouse movements etc) – so far my tests have been to do with collections.&lt;/p&gt;  &lt;p&gt;My disappointed half thinks it&amp;#39;s missing something. You see, Reactive Extensions shares some concepts with my own &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation.aspx"&gt;Push LINQ&lt;/a&gt; library… except it&amp;#39;s had smarter people (no offense meant to Marc Gravell) working harder on it for longer. I&amp;#39;d expect it to be easier to use, and make it a breeze to do anything you could do in Push LINQ. Unfortunately, that&amp;#39;s not quite the case.&lt;/p&gt;  &lt;h3&gt;Subscription model&lt;/h3&gt;  &lt;p&gt;First, the way that subscription is handled for collections seems slightly odd. I&amp;#39;ve been imagining two kinds of observable sources:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Genuine &amp;quot;event streams&amp;quot; which occur somewhat naturally – for instance, mouse movement events. Subscribing to such an observable wouldn&amp;#39;t do anything to it other than adding subscribers. &lt;/li&gt;    &lt;li&gt;Collections (and the like) where the usual use case is &amp;quot;set up the data pipeline, then tell it to go&amp;quot;. In that case calling Subscribe should just add the relevant observers, but not actually &amp;quot;start&amp;quot; the sequence – after all, you may want to add more observers (we&amp;#39;ll see an example of this in a minute). &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In the latter case, I could imagine an extension method to &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; called ToObservable which would return a StartableObservable&amp;lt;T&amp;gt; or something like that – you&amp;#39;d subscribe what you want, and then call Start on the &lt;code&gt;StartableObservable&amp;lt;T&amp;gt;&lt;/code&gt;. That&amp;#39;s not what appears to happen though – if you call &lt;code&gt;ToObservable()&lt;/code&gt;, you get an implementation which iterates over the source sequence as soon as anything subscribes to it – which just doesn&amp;#39;t feel right to me. Admittedly it makes life easy in the case where that&amp;#39;s really all you want to do, but it&amp;#39;s a pain otherwise.&lt;/p&gt;  &lt;p&gt;There&amp;#39;s a way of working round this in Reactive Extensions: there&amp;#39;s &lt;code&gt;Subject&amp;lt;T&amp;gt;&lt;/code&gt; which is both an observer and an observable. You can create a &lt;code&gt;Subject&amp;lt;T&amp;gt;&lt;/code&gt;, Subscribe all the observers you want (so as to set up the data pipeline) and then subscribe the subject to the real data source. It&amp;#39;s not exactly hard, but it took me a while to work out, and it feels a little unwieldy. The next issue was somewhat more problematic.&lt;/p&gt;  &lt;h3&gt;Blocking aggregation&lt;/h3&gt;  &lt;p&gt;When I first started thinking about Push LINQ, it was motivated by a scenario from the C# newsgroup: someone wanted to group a collection in a particular way, and then count how many items were in each group. This is effectively the &amp;quot;favourite colour voting&amp;quot; scenario outlined in the link at the top of this post. The problem to understand is that the normal &lt;code&gt;Count()&lt;/code&gt; call is blocking: it fetches items from a collection until there aren&amp;#39;t any more; it&amp;#39;s in control of the execution flow, effectively. That means if you call it in a grouping construct, the whole group has to be available before you call &lt;code&gt;Count()&lt;/code&gt;. So, you can&amp;#39;t stream an enormous data set, which is unfortunate.&lt;/p&gt;  &lt;p&gt;In Push LINQ, I addressed this by making &lt;code&gt;Count()&lt;/code&gt; return &lt;code&gt;Future&amp;lt;int&amp;gt;&lt;/code&gt; instead of &lt;code&gt;int&lt;/code&gt;. The whole query is evaluated, and &lt;em&gt;then&lt;/em&gt; you can ask each future for its actual result. Unfortunately, that isn&amp;#39;t the approach that the Reactive Framework has taken – it still returns &lt;code&gt;int&lt;/code&gt; from &lt;code&gt;Count()&lt;/code&gt;. I don&amp;#39;t know the reason for this, but fortunately it&amp;#39;s somewhat fixable. We can&amp;#39;t change &lt;code&gt;Observable&lt;/code&gt; of course, but we can add our own future-based extensions:&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; ObservableEx     &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; Task&amp;lt;TResult&amp;gt; FutureAggregate&amp;lt;TSource, TResult&amp;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; IObservable&amp;lt;TSource&amp;gt; source,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; TResult seed, Func&amp;lt;TResult, TSource, TResult&amp;gt; aggregation)     &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; TaskCompletionSource&amp;lt;TResult&amp;gt; result = &lt;span class="Keyword"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;TResult&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; TResult current = seed;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; source.Subscribe(value =&amp;gt; current = aggregation(current, value),     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; error =&amp;gt; result.SetException(error),     &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;gt; result.SetResult(current));     &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; result.Task;     &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;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; FutureMax(&lt;span class="Keyword"&gt;this&lt;/span&gt; IObservable&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; source)     &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: Make this generic and throw exception on&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;// empty sequence. Left as an exercise for the reader.&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;return&lt;/span&gt; source.FutureAggregate(&lt;span class="ValueType"&gt;int&lt;/span&gt;.MinValue, Math.Max);     &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;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; FutureMin(&lt;span class="Keyword"&gt;this&lt;/span&gt; IObservable&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; source)     &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: Make this generic and throw exception on&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;// empty sequence. Left as an exercise for the reader.&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;return&lt;/span&gt; source.FutureAggregate(&lt;span class="ValueType"&gt;int&lt;/span&gt;.MaxValue, Math.Min);     &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;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; Task&amp;lt;&lt;span class="ValueType"&gt;int&lt;/span&gt;&amp;gt; FutureCount&amp;lt;T&amp;gt;(&lt;span class="Keyword"&gt;this&lt;/span&gt; IObservable&amp;lt;T&amp;gt; source)     &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;return&lt;/span&gt; source.FutureAggregate(0, (count, _) =&amp;gt; count + 1);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;This uses &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; from Parallel Extensions, which gives us an interesting ability, as we&amp;#39;ll see in a moment. It&amp;#39;s all fairly straightforward - &lt;code&gt;TaskCompletionSource&amp;lt;T&amp;gt;&lt;/code&gt; makes it very easy to specify a value when we&amp;#39;ve finished, or indicate that an error occurred. As mentioned in the comments, the maximum/minimum implementations leave something to be desired, but it&amp;#39;s good enough for a blog post :) &lt;/p&gt;  &lt;h3&gt;Using the non-blocking aggregation operators&lt;/h3&gt;  &lt;p&gt;Now that we&amp;#39;ve got our extension methods, how can we use them? First I decided to do a demo which would count the number of lines in a file, and find the maximum and minimum line lengths:&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; List&amp;lt;T&amp;gt; ToList&amp;lt;T&amp;gt;(&lt;span class="Keyword"&gt;this&lt;/span&gt; IObservable&amp;lt;T&amp;gt; source)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; List&amp;lt;T&amp;gt; ret = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;T&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; source.Subscribe(x =&amp;gt; ret.Add(x));     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; ret;     &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; IEnumerable&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt; ReadLines(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; filename)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Namespace"&gt;using&lt;/span&gt; (TextReader reader = File.OpenText(filename))     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; line;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;while&lt;/span&gt; ((line = reader.ReadLine()) != &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;yield&lt;/span&gt;&amp;#160;&lt;span class="Statement"&gt;return&lt;/span&gt; line;     &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;...     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; subject = &lt;span class="Keyword"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; lengths = subject.Select(line =&amp;gt; line.Length);     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; min = lengths.FutureMin();     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; max = lengths.FutureMax();     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; count = lengths.FutureCount();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; source = ReadLines(&lt;span class="String"&gt;&amp;quot;../../Program.cs&amp;quot;&lt;/span&gt;);     &lt;br /&gt;source.ToObservable(Scheduler.Now).Subscribe(subject);     &lt;br /&gt;Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Count: {0}, Min: {1}, Max: {2}&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;&amp;#160;&amp;#160; count.Result, min.Result, max.Result); &lt;/div&gt;  &lt;p&gt;As you can see, we use the &lt;code&gt;Result&lt;/code&gt; property of a task to find its eventual result - this call will block until the result is ready, however, so you do need to be careful about how you use it. Each line is only read from the file once, and pushed to all three observers, who carry their state around until the sequence is complete, whereupon they publish the result to the task.&lt;/p&gt;  &lt;p&gt;I got this working fairly quickly - then went back to the &amp;quot;grouping lines by line length&amp;quot; problem I&amp;#39;d originally set myself. I want to group the lines of a file by their length (all lines of length 0, all lines of length 1 etc) and count each group. The result is effectively a histogram of line lengths. Constructing the query itself wasn&amp;#39;t a problem - but iterating through the results was. Fundamentally, I don&amp;#39;t understand the details of &lt;code&gt;ToEnumerable&lt;/code&gt; yet, particularly the timing. I need to look into it more deeply, but I&amp;#39;ve got two alternative solutions for the moment. &lt;/p&gt;  &lt;p&gt;The first is to implement my own &lt;code&gt;ToList&lt;/code&gt; extension method. This simply creates a list and subscribes an observer which adds items to the list as it goes. There&amp;#39;s no attempt at &amp;quot;safety&amp;quot; here - if you access the list before the source sequence has completed, you&amp;#39;ll see whatever has been added so far. I &lt;i&gt;am&lt;/i&gt; still just experimenting :) Here&amp;#39;s the implementation: &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; List&amp;lt;T&amp;gt; ToList&amp;lt;T&amp;gt;(&lt;span class="Keyword"&gt;this&lt;/span&gt; IObservable&amp;lt;T&amp;gt; source)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; List&amp;lt;T&amp;gt; ret = &lt;span class="Keyword"&gt;new&lt;/span&gt; List&amp;lt;T&amp;gt;();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; source.Subscribe(x =&amp;gt; ret.Add(x));     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; ret;     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Now we can construct a query expression, project each group using our future count, make sure we&amp;#39;ve finished pushing the source before we read the results, and everything is fine:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; subject = &lt;span class="Keyword"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; groups = &lt;span class="Linq"&gt;from&lt;/span&gt; line &lt;span class="Statement"&gt;in&lt;/span&gt; subject     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;group&lt;/span&gt; line.Length &lt;span class="Linq"&gt;by&lt;/span&gt; line.Length &lt;span class="Linq"&gt;into&lt;/span&gt; grouped     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;select&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; { Length = grouped.Key, Count = grouped.FutureCount() };     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; results = groups.ToList();     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; source = ReadLines(&lt;span class="String"&gt;&amp;quot;../../Program.cs&amp;quot;&lt;/span&gt;);     &lt;br /&gt;source.ToObservable(Scheduler.Now).Subscribe(subject);     &lt;br /&gt;&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; results)     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Length: {0}; Count: {1}&amp;quot;&lt;/span&gt;, &lt;span class="Linq"&gt;group&lt;/span&gt;.Length, &lt;span class="Linq"&gt;group&lt;/span&gt;.Count.Result);     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Note how the call to &lt;code&gt;ToList&lt;/code&gt; is required &lt;i&gt;before&lt;/i&gt; calling &lt;code&gt;source.ToObservable(...).Subscribe&lt;/code&gt; - otherwise everything would have been pushed before we started collecting it.&lt;/p&gt;  &lt;p&gt;All well and good... but there&amp;#39;s another way of doing it too. We&amp;#39;ve only got a single task being produced for each group - instead of waiting until everything&amp;#39;s finished before we dump the results to the console, we can use &lt;code&gt;Task.ContinueWith&lt;/code&gt; to write it (the individual group result) out as soon as that group has been told that it&amp;#39;s finished. We force this extra action to occur on the same thread as the observer just to make things easier in a console app... but it all works very neatly: &lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; subject = &lt;span class="Keyword"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;();     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; groups = &lt;span class="Linq"&gt;from&lt;/span&gt; line &lt;span class="Statement"&gt;in&lt;/span&gt; subject     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;group&lt;/span&gt; line.Length &lt;span class="Linq"&gt;by&lt;/span&gt; line.Length &lt;span class="Linq"&gt;into&lt;/span&gt; grouped     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;select&lt;/span&gt;&amp;#160;&lt;span class="Keyword"&gt;new&lt;/span&gt; { Length = grouped.Key, Count = grouped.FutureCount() };     &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; &lt;br /&gt;groups.Subscribe(&lt;span class="Linq"&gt;group&lt;/span&gt; =&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;group&lt;/span&gt;.Count.ContinueWith(     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; x =&amp;gt; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Length: {0}; Count: {1}&amp;quot;&lt;/span&gt;,&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Linq"&gt;group&lt;/span&gt;.Length, x.Result),     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; TaskContinuationOptions.ExecuteSynchronously);     &lt;br /&gt;});     &lt;br /&gt;&lt;span class="Linq"&gt;var&lt;/span&gt; source = ReadLines(&lt;span class="String"&gt;&amp;quot;../../Program.cs&amp;quot;&lt;/span&gt;);     &lt;br /&gt;source.ToObservable(Scheduler.Now).Subscribe(subject); &lt;/div&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;That&amp;#39;s the lot, so far. It feels like I&amp;#39;m &lt;i&gt;sort of&lt;/i&gt; in the spirit of Reactive Extensions, but that maybe I&amp;#39;m pushing it (no pun intended) in a direction which Erik and Wes either didn&amp;#39;t anticipate, or at least don&amp;#39;t view as particularly valuable/elegant. I very much doubt that they didn&amp;#39;t &lt;i&gt;consider&lt;i&gt; deferred aggregates - it&amp;#39;s much more likely that either I&amp;#39;ve missed some easy way of doing this, or there are good reasons why it&amp;#39;s a bad idea. I hope to find out which at some point... but in the meantime, I really ought to work out a more idiomatic example for C# in Depth. &lt;/i&gt;&lt;/i&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1752014" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Books/default.aspx">Books</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/LINQ/default.aspx">LINQ</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>Contract classes and nested types within interfaces</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/10/31/contract-classes-and-nested-types-within-interfaces.aspx</link><pubDate>Sat, 31 Oct 2009 22:04:54 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1736652</guid><dc:creator>skeet</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1736652</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1736652</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/10/31/contract-classes-and-nested-types-within-interfaces.aspx#comments</comments><description>&lt;p&gt;I&amp;#39;ve just been going through some feedback for the draft copy of the second edition of C# in Depth. In the contracts section, I have an example like this:&lt;/p&gt;  &lt;div class="code"&gt;[ContractClass(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(ICaseConverterContracts))]     &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; ICaseConverter     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; Convert(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; text);     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;[ContractClassFor(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(ICaseConverter))]     &lt;br /&gt;&lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; ICaseConverterContracts : ICaseConverter     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; ICaseConverter.Convert(&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; Contract.Requires(text != &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; Contract.Ensures(Contract.Result&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;() != &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;return&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;default&lt;/span&gt;(&lt;span class="ReferenceType"&gt;string&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="Modifier"&gt;private&lt;/span&gt; ICaseConverterContracts() {}     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; InvariantUpperCaseFormatter : ICaseConverter     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; Convert(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; text)&amp;#160; &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;return&lt;/span&gt; text.ToUpperInvariant();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The point is to demonstrate how contracts can be specified for interfaces, and then applied automatically to implementations. In this case, &lt;code&gt;ICaseConverter&lt;/code&gt; is the interface, &lt;code&gt;ICaseConverterContracts&lt;/code&gt; is the &lt;i&gt;contract class&lt;/i&gt; which specifies the contract for the interface, and &lt;code&gt;InvariantUpperCaseFormatter&lt;/code&gt; is the real implementation. The binary rewriter effectively copies the contract into each implementation, so you don&amp;#39;t need to duplicate the contract in the source code.&lt;/p&gt;  &lt;p&gt;The reader feedback asked where the contract class code should live - should it go in the same file as the interface itself, or in a separate file as normal? Now normally, I&amp;#39;m firmly of the &amp;quot;one top-level type per file&amp;quot; persuasion, but in this case I think it makes sense to keep the contract class with the interface. It has no meaning without reference to the interface, after all - it&amp;#39;s not a real implementation to be used in the normal way. It&amp;#39;s essentially metadata. This does, however, leave me feeling a little bit dirty. What I&amp;#39;d &lt;em&gt;really&lt;/em&gt; like to be able to do is nest the contract class inside the interface, just like I do with other classes which are tightly coupled to an &amp;quot;owner&amp;quot; type. Then the code would look like this:&lt;/p&gt;  &lt;div class="code"&gt;[ContractClass(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(ICaseConverterContracts))]     &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; ICaseConverter     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; Convert(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; text);     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [ContractClassFor(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(ICaseConverter))]     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; ICaseConverterContracts : ICaseConverter     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; ICaseConverter.Convert(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; text)     &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; Contract.Requires(text != &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; Contract.Ensures(Contract.Result&amp;lt;&lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;() != &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; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;default&lt;/span&gt;(&lt;span class="ReferenceType"&gt;string&lt;/span&gt;);     &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;private&lt;/span&gt; ICaseConverterContracts() {}     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; InvariantUpperCaseFormatter : ICaseConverter     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; Convert(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; text)&amp;#160; &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;return&lt;/span&gt; text.ToUpperInvariant();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;That would make me feel happier - all the information to do with the interface would be specified within the interface type&amp;#39;s code. It&amp;#39;s possible that with that as a convention, the Code Contracts tooling could cope without the attributes - if interface &lt;code&gt;IFoo&lt;/code&gt; contains a nested class &lt;code&gt;IFooContracts&lt;/code&gt; which implements &lt;code&gt;IFoo&lt;/code&gt;, assume it&amp;#39;s a contract class and handle it appropriately. That would be sweet.&lt;/p&gt;  &lt;p&gt;You know the really galling thing? I&amp;#39;m pretty sure VB &lt;em&gt;does&lt;/em&gt; allow nested types in interfaces...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1736652" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Books/default.aspx">Books</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+4/default.aspx">C# 4</category></item><item><title>Iterating atomically</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/10/23/iterating-atomically.aspx</link><pubDate>Fri, 23 Oct 2009 21:20:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1734632</guid><dc:creator>skeet</dc:creator><slash:comments>34</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1734632</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1734632</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/10/23/iterating-atomically.aspx#comments</comments><description>&lt;p&gt;The IEnumerable&amp;lt;T&amp;gt; and IEnumerator&amp;lt;T&amp;gt; interfaces in .NET are interesting. They crop up an awful lot, but hardly anyone ever calls them directly - you almost always use a foreach loop to iterate over the collection. That hides all the calls to GetEnumerator(), MoveNext() and Current. Likewise iterator blocks hide the details when you want to implement the interfaces. However, sometimes details matter - such as for &lt;a href="http://stackoverflow.com/questions/1605745"&gt;this recent Stack Overflow question&lt;/a&gt;. The question asks how to create a thread-safe iterator - one that can be called from multiple threads. This is not about iterating over a collection &lt;em&gt;n&lt;/em&gt; times independently on &lt;em&gt;n&lt;/em&gt; different threads - this is about iterating over a collection &lt;em&gt;once&lt;/em&gt; without skipping or duplicating. Imagine it&amp;#39;s some set of jobs that we have to complete. We assume that the iterator itself is thread-safe to the extent that calls from different threads &lt;em&gt;at different times, with intervening locks&lt;/em&gt; will be handled reasonably. This is reasonable - basically, so long as it isn&amp;#39;t going out of its way to be thread-hostile, we should be okay. We also assume that no-one is trying to write to the collection at the same time.&lt;/p&gt;
&lt;p&gt;Sounds easy, right? Well, no... because the IEnumerator&amp;lt;T&amp;gt; interface has two members which we effectively want to call atomically. In particular, we &lt;em&gt;don&amp;#39;t&lt;/em&gt; want the collection { &amp;quot;a&amp;quot;, &amp;quot;b&amp;quot; } to be iterated like this:&lt;/p&gt;
&lt;table width="400" cellpadding="2" cellspacing="0" border="0"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td width="200" valign="top"&gt;Thread 1&lt;/td&gt;
&lt;td width="200" valign="top"&gt;Thread 2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="200" valign="top"&gt;MoveNext()&lt;/td&gt;
&lt;td width="200" valign="top"&gt;&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="200" valign="top"&gt;&amp;nbsp;&lt;/td&gt;
&lt;td width="200" valign="top"&gt;MoveNext()&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="200" valign="top"&gt;Current&lt;/td&gt;
&lt;td width="200" valign="top"&gt;&amp;nbsp;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="200" valign="top"&gt;&amp;nbsp;&lt;/td&gt;
&lt;td width="200" valign="top"&gt;Current&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;That way we&amp;#39;ll end up not processing the first item at all, and the second item twice.&lt;/p&gt;
&lt;p&gt;There are two ways of approaching this problem. In both cases I&amp;#39;ve started with IEnumerable&amp;lt;T&amp;gt; for consistency, but in fact it&amp;#39;s IEnumerator&amp;lt;T&amp;gt; which is the interesting bit. In particular, we&amp;#39;re not going to be able to iterate over our result anyway, as each thread needs to have the same IEnumerator&amp;lt;T&amp;gt; - which it won&amp;#39;t do if each of them uses foreach (which calls GetEnumerator() to start with).&lt;/p&gt;
&lt;h3&gt;Fix the interface&lt;/h3&gt;
&lt;p&gt;First we&amp;#39;ll try to fix the interface to look how it should have looked to start with, at least from the point of view of atomicity. Here are the new interfaces:&lt;/p&gt;
&lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; IAtomicEnumerable&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IAtomicEnumerator&amp;lt;T&amp;gt; GetEnumerator();     &lt;br /&gt;}     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; IAtomicEnumerator&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ValueType"&gt;bool&lt;/span&gt; TryMoveNext(&lt;span class="MethodParameter"&gt;out&lt;/span&gt; T nextValue);     &lt;br /&gt;} &lt;/div&gt;
&lt;p&gt;One thing you may notice is that we&amp;#39;re not implementing IDisposable. That&amp;#39;s basically because it&amp;#39;s a pain to do so when you think about a multi-threaded environment. Indeed, it&amp;#39;s possibly one of the biggest arguments against something of this nature. At what point do you dispose? Just because &lt;em&gt;one&lt;/em&gt; thread finished doesn&amp;#39;t mean that the rest of them have... don&amp;#39;t forget that &amp;quot;finish&amp;quot; might mean &amp;quot;an exception was thrown while processing the job, I&amp;#39;m bailing out&amp;quot;. You&amp;#39;d need some sort of co-ordinator to make sure that &lt;em&gt;everyone&lt;/em&gt; is finished before you actually do any clean-up. Anyway, the nice thing about this being a blog post is we can ignore that little thorny issue :)&lt;/p&gt;
&lt;p&gt;The important point is that we now have a single method in IAtomicEnumerator&amp;lt;T&amp;gt; - TryMoveNext, which works the way you&amp;#39;d expect it to. It atomically attempts to move to the next item, returns whether or not it succeeded, and sets an out parameter with the next value if it &lt;em&gt;did&lt;/em&gt; succeed. Now there&amp;#39;s no chance of two threads using the method and stomping on each other&amp;#39;s values (unless they&amp;#39;re silly and use the same variable for the out parameter).&lt;/p&gt;
&lt;p&gt;It&amp;#39;s reasonably easy to wrap the standard interfaces in order to implement this interface:&lt;/p&gt;
&lt;div class="code"&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// Wraps a normal IEnumerable[T] up to implement IAtomicEnumerable[T].&lt;/span&gt;     &lt;br /&gt;&lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; AtomicEnumerable&amp;lt;T&amp;gt; : IAtomicEnumerable&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; original;     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; AtomicEnumerable(IEnumerable&amp;lt;T&amp;gt; original)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Keyword"&gt;this&lt;/span&gt;.original = original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; IAtomicEnumerator&amp;lt;T&amp;gt; GetEnumerator()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt; AtomicEnumerator(original.GetEnumerator());     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="XmlComment"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="XmlComment"&gt;/// Implementation of IAtomicEnumerator[T] to wrap IEnumerator[T].&lt;/span&gt;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="XmlComment"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; AtomicEnumerator : IAtomicEnumerator&amp;lt;T&amp;gt;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; IEnumerator&amp;lt;T&amp;gt; original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;object&lt;/span&gt; padlock = &lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;object&lt;/span&gt;();     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;internal&lt;/span&gt; AtomicEnumerator(IEnumerator&amp;lt;T&amp;gt; original)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Keyword"&gt;this&lt;/span&gt;.original = original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;bool&lt;/span&gt; TryMoveNext(&lt;span class="MethodParameter"&gt;out&lt;/span&gt; T value)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;lock&lt;/span&gt; (padlock)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ValueType"&gt;bool&lt;/span&gt; hadNext = original.MoveNext();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; value = hadNext ? original.Current : &lt;span class="Modifier"&gt;default&lt;/span&gt;(T);     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt; hadNext;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;} &lt;/div&gt;
&lt;p&gt;Just ignore the fact that I never dispose of the original IEnumerator&amp;lt;T&amp;gt; :)&lt;/p&gt;
&lt;p&gt;We use a simple lock to make sure that MoveNext() and Current always happen together - that nothing else is going to call MoveNext() between our TryMoveNext() calling it, and it fetching the current value.&lt;/p&gt;
&lt;p&gt;Obviously you&amp;#39;d need to write your own code to actually &lt;em&gt;use&lt;/em&gt; this sort of iterator, but it would be quite simple:&lt;/p&gt;
&lt;div class="code"&gt;T value;    &lt;br /&gt;&lt;span class="Statement"&gt;while&lt;/span&gt; (iterator.TryMoveNext(&lt;span class="MethodParameter"&gt;out&lt;/span&gt; value))     &lt;br /&gt;{     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="InlineComment"&gt;// Use value&lt;/span&gt;     &lt;br /&gt;} &lt;/div&gt;
&lt;p&gt;However, you may already have code which wants to use an IEnumerator&amp;lt;T&amp;gt;. Let&amp;#39;s see what else we can do.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Using thread local variables to fake it&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;.NET 4.0 has a very useful type called ThreadLocal&amp;lt;T&amp;gt;. It does basically what you&amp;#39;d expect it to, with nice features such as being able to supply a delegate to be executed on each thread to provide the initial value. We can use a thread local to make sure that so long as we call both MoveNext() and Current atomically when we&amp;#39;re asked to move to the next element, we can get back the right value for Current later on. It has to be thread local because we&amp;#39;re sharing a single IEnumerator&amp;lt;T&amp;gt; across multiple threads - each needs its own separate storage.&lt;/p&gt;
&lt;p&gt;This is also the approach we&amp;#39;d use if we wanted to wrap an IAtomicEnumerator&amp;lt;T&amp;gt; in an IEnumerator&amp;lt;T&amp;gt;, by the way. Here&amp;#39;s the code to do it:&lt;/p&gt;
&lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; ThreadSafeEnumerable&amp;lt;T&amp;gt; : IEnumerable&amp;lt;T&amp;gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; original;     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; ThreadSafeEnumerable(IEnumerable&amp;lt;T&amp;gt; original)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Keyword"&gt;this&lt;/span&gt;.original = original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; IEnumerator&amp;lt;T&amp;gt; GetEnumerator()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt; ThreadSafeEnumerator(original.GetEnumerator());     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; IEnumerator IEnumerable.GetEnumerator()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt; GetEnumerator();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;sealed&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; ThreadSafeEnumerator : IEnumerator&amp;lt;T&amp;gt;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; IEnumerator&amp;lt;T&amp;gt; original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;object&lt;/span&gt; padlock = &lt;span class="Keyword"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;object&lt;/span&gt;();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;readonly&lt;/span&gt; ThreadLocal&amp;lt;T&amp;gt; current = &lt;span class="Keyword"&gt;new&lt;/span&gt; ThreadLocal&amp;lt;T&amp;gt;();     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;internal&lt;/span&gt; ThreadSafeEnumerator(IEnumerator&amp;lt;T&amp;gt; original)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Keyword"&gt;this&lt;/span&gt;.original = original;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;bool&lt;/span&gt; MoveNext()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;lock&lt;/span&gt; (padlock)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ValueType"&gt;bool&lt;/span&gt; ret = original.MoveNext();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;if&lt;/span&gt; (ret)     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; current.Value = original.Current;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt; ret;     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; T Current     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; get { &lt;span class="Statement"&gt;return&lt;/span&gt; current.Value; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;void&lt;/span&gt; Dispose()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; original.Dispose();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; current.Dispose();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ReferenceType"&gt;object&lt;/span&gt; IEnumerator.Current     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; get { &lt;span class="Statement"&gt;return&lt;/span&gt; Current; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;    &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;void&lt;/span&gt; Reset()     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt; NotSupportedException();     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }     &lt;br /&gt;} &lt;/div&gt;
&lt;p&gt;I&amp;#39;m going to say it one last time - we&amp;#39;re broken when it comes to disposal. There&amp;#39;s no way of &lt;em&gt;safely&lt;/em&gt; disposing of the original iterator at &amp;quot;just the right time&amp;quot; when everyone&amp;#39;s finished with it. Oh well.&lt;/p&gt;
&lt;p&gt;Other than that, it&amp;#39;s quite simple. This code has the serendipitous property of actually implementing IEnumerator&amp;lt;T&amp;gt; slightly better than C#-compiler-generated implementations from iterator blocks - if you call the Current property without having called MoveNext(), this will throw an InvalidOperationException, just as the documentation says it should. (It doesn&amp;#39;t do the same at the end, admittedly, but that&amp;#39;s fixable if we really wanted to be pedantic.&lt;/p&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;I found this an intriguing little problem. I think there are better ways of solving the bigger picture - a co-ordinator which takes care of disposing exactly once, and which possibly mediates the original iterator etc is probably the way forward... but I enjoyed thinking about the nitty gritty.&lt;/p&gt;
&lt;p&gt;Generally speaking, I prefer the first of these approaches. Thread local variables always feel like a bit of a grotty hack to me - they can be useful, but it&amp;#39;s better to avoid them if you can. It&amp;#39;s interesting to see how an interface can be inherently thread-friendly or not.&lt;/p&gt;
&lt;p&gt;One last word of warning - this code is &lt;em&gt;completely&lt;/em&gt; untested. It builds, and I can&amp;#39;t immediately see why it wouldn&amp;#39;t work, but I&amp;#39;m making no guarantees...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1734632" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Parallelisation/default.aspx">Parallelisation</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category></item><item><title>An object lesson in blogging and accuracy; was: Efficient "vote counting" with LINQ to Objects - and the value of nothing</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/09/20/efficient-quot-vote-counting-quot-with-linq-to-objects-and-the-value-of-nothing.aspx</link><pubDate>Sun, 20 Sep 2009 20:48:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1725262</guid><dc:creator>skeet</dc:creator><slash:comments>11</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1725262</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1725262</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/09/20/efficient-quot-vote-counting-quot-with-linq-to-objects-and-the-value-of-nothing.aspx#comments</comments><description>&lt;p&gt;Well, this is embarrassing.&lt;/p&gt;  &lt;p&gt;Yesterday evening, I excitedly wrote a blog post about an interesting little idea for making a particular type of LINQ query (basically vote counting) efficient. It was an idea that had occurred to me a few months back, but I hadn&amp;#39;t got round to blogging about it.&lt;/p&gt;  &lt;p&gt;The basic idea was to take a completely empty struct, and use that as the element type in the results of a grouping query - as the struct was empty, it would take no space, therefore &amp;quot;huge&amp;quot; arrays could be created for no cost beyond the fixed array overhead, etc. I carefully checked that the type used for grouping did in fact implement ICollection&amp;lt;T&amp;gt; so that the Count method would be efficient; I wrote sample code which made sure my queries were valid... but I failed to check that the empty struct &lt;em&gt;really&lt;/em&gt; took up no memory.&lt;/p&gt;  &lt;p&gt;Fortunately, I have smart readers, a number of whom pointed out my mistake in very kind terms.&lt;/p&gt;  &lt;p&gt;Ben Voigt gave the reason for the size being 1 in a comment:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The object identity rules require a unique address for each instance... identity can be shared with super- or sub- class objects (Empty Base Optimization) but the total size of the instance has to be at least 1.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This makes perfect sense - it&amp;#39;s just a shame I didn&amp;#39;t realise it before.&lt;/p&gt;  &lt;p&gt;Live and learn, I guess - but apologies for the poorly researched post. I&amp;#39;ll attempt to be more careful next time.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1725262" 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/LINQ/default.aspx">LINQ</category></item><item><title>Generic constraints for enums and delegates</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx</link><pubDate>Thu, 10 Sep 2009 20:09:00 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1722426</guid><dc:creator>skeet</dc:creator><slash:comments>56</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1722426</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1722426</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx#comments</comments><description>&lt;p&gt;As most readers probably know, C# prohibits generic type constraints from referring to System.Object, System.Enum, System.Array, System.Delegate and System.ValueType. In other words, this method declaration is illegal:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; T[] GetValues&amp;lt;T&amp;gt;() &lt;span class="Linq"&gt;where&lt;/span&gt; T : struct, System.Enum    &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; (T[]) Enum.GetValues(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(T));     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;This is a pity, as such a method could be useful. (In fact there are better things we can do... such as returning a read-only collection. That way we don&amp;#39;t have to create a new array each time the method is called.) As far as I can tell, there is no reason why this should be prohibited. Eric Lippert has stated that he believes &lt;a href="http://stackoverflow.com/questions/1331739/enum-type-constraints-in-c/1331811#1331811"&gt;the CLR doesn&amp;#39;t support this&lt;/a&gt; - but I think he&amp;#39;s wrong. I can&amp;#39;t remember the last time I had cause to believe Eric to be wrong about something, and I&amp;#39;m somewhat nervous of even mentioning it, but section 10.1.7 of the CLI spec (&lt;a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm"&gt;ECMA-335&lt;/a&gt;) partition II (p40) &lt;em&gt;specifically&lt;/em&gt; gives examples of type parameter constraints involving System.Delegate and System.Enum. It introduces the table with &amp;quot;The following table shows the valid combinations of type and special constraints for a representative set of types.&amp;quot; It was only due to reading this table that I realized that the value type constraint on the above is required (or a constructor constraint would do equally well) - otherwise System.Enum itself satisfies the constraint, which would be a Bad Thing.&lt;/p&gt;  &lt;p&gt;It&amp;#39;s possible (but unlikely) that the CLI doesn&amp;#39;t fully implement this part of the CLR spec. I&amp;#39;m hoping that Eric&amp;#39;s just wrong on this occasion, and that actually there&amp;#39;s nothing to stop the C# language from allowing such constraints in the future. (It would be nice to get keyword support, such that a constraint of &amp;quot;T : enum&amp;quot; would be equivalent to the above, but hey...)&lt;/p&gt;  &lt;p&gt;The good news is that ilasm/ildasm have no problem with this. The better news is that if you add a reference to a library which uses those constraints, the C# compiler applies them sensibly, as far as I can tell...&lt;/p&gt;  &lt;h3&gt;Introducing UnconstrainedMelody&lt;/h3&gt;  &lt;p&gt;(Okay, the name will almost surely have to change. But I like the idea of it removing the constraints of C# around which constraints are valid... and yet still being in the key of C#. Better suggestions welcome.)&lt;/p&gt;  &lt;p&gt;I have a plan - I want to write a utility library which does useful things for enums and delegates (and arrays if I can think of anything sensible to do with them). It will be written in C#, with methods like this:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt; T[] GetValues&amp;lt;T&amp;gt;() &lt;span class="Linq"&gt;where&lt;/span&gt; T : struct, IEnumConstraint    &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;return&lt;/span&gt; (T[]) Enum.GetValues(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(T));     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;(IEnumConstraint has to be an interface of course, as otherwise the constraint would be invalid.)&lt;/p&gt;  &lt;p&gt;As a post-build step, I will:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Run ildasm on the resulting binary &lt;/li&gt;    &lt;li&gt;Replace every constraint using EnumConstraint with System.Enum &lt;/li&gt;    &lt;li&gt;Run ilasm to build the binary again &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;If anyone has a &lt;em&gt;simple&lt;/em&gt; binary rewriter (I&amp;#39;ve looked at &lt;a href="http://postsharp.org"&gt;PostSharp&lt;/a&gt; and &lt;a href="http://cciast.codeplex.com/license"&gt;CCI&lt;/a&gt;; both look &lt;em&gt;way&lt;/em&gt; more complicated than the above) which would do this, that would be great. Otherwise ildasm/ilasm will be fine. It&amp;#39;s not like &lt;em&gt;consumers&lt;/em&gt; will need to perform this step.&lt;/p&gt;  &lt;p&gt;As soon as the name is finalized I&amp;#39;ll add a project on Google Code. Once the infrastructure is in place, adding utility methods should be very straightforward. Suggestions for utility methods would be useful, or just join the project when it&amp;#39;s up and running.&lt;/p&gt;  &lt;p&gt;Am I being silly? Have I overlooked something?&lt;/p&gt;  &lt;h3&gt;A couple of hours later...&lt;/h3&gt;  &lt;p&gt;Okay, I decided not to wait for a better name. The first cut - which does basically nothing but validate the idea, and the fact that I can still unit test it - is in. The &lt;a href="http://code.google.com/p/unconstrained-melody"&gt;UnconstrainedMelody Google Code project&lt;/a&gt; is live!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1722426" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category></item><item><title>The "dream book" for C# and .NET</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/08/20/the-quot-dream-book-quot-for-c-and-net.aspx</link><pubDate>Thu, 20 Aug 2009 16:57:40 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1716905</guid><dc:creator>skeet</dc:creator><slash:comments>34</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1716905</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1716905</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/08/20/the-quot-dream-book-quot-for-c-and-net.aspx#comments</comments><description>&lt;p&gt;This morning I &lt;a href="http://twitter.com/jonskeet/status/3424128643"&gt;showed my hand a little on Twitter&lt;/a&gt;. I&amp;#39;ve had a dream for a long time about the ultimate C# book. It&amp;#39;s a dream based on &lt;a href="http://www.amazon.com/dp/0321356683"&gt;Effective Java&lt;/a&gt;, which is my favourite Java book, along with my experiences of writing C# in Depth.&lt;/p&gt;  &lt;p&gt;Effective Java is written by Josh Bloch, who is an absolute giant in the Java world... and that&amp;#39;s both the problem and the opportunity. There&amp;#39;s no-one of quite the equivalent stature in the .NET world. Instead, there are many very smart people, a lot of whom blog and some of whom have their own books.&lt;/p&gt;  &lt;p&gt;There are &amp;quot;best practices&amp;quot; books, of course: Microsoft&amp;#39;s own Framework Design Guidelines, and Bill Wagner&amp;#39;s &lt;a href="http://www.amazon.com/dp/0321245660"&gt;Effective C#&lt;/a&gt; and &lt;a href="http://www.amazon.com/dp/0321485890"&gt;More Effective C#&lt;/a&gt; being the most obvious examples. I&amp;#39;m in no way trying to knock these books, but I feel we could do even better. The &lt;a href="http://www.amazon.com/dp/0321246756"&gt;Framework Design Guidelines&lt;/a&gt; (also available &lt;a href="http://msdn.microsoft.com/en-us/library/ms229042.aspx"&gt;free to browse on MSDN&lt;/a&gt;) are really about how to create a good API - which is important, but not the be-all-and-end-all for many &lt;em&gt;application&lt;/em&gt; developers who aren&amp;#39;t trying to ship a reusable class library and may well have different concerns. They want to know how to use the &lt;em&gt;language&lt;/em&gt; most effectively, as well as the core types within the framework.&lt;/p&gt;  &lt;p&gt;Bill&amp;#39;s books - and many others which cover the core framework, such as &lt;a href="http://www.amazon.com/dp/0735621632"&gt;CLR via C#&lt;/a&gt;, &lt;a href="http://www.amazon.com/dp/1590598733"&gt;Accelerated C# 2008&lt;/a&gt; and &lt;a href="http://www.amazon.com/dp/0596527578"&gt;C# 3.0 in a Nutshell&lt;/a&gt; - give plenty of advice, but often I&amp;#39;ve felt it&amp;#39;s a little one-sided. Each of these books is the work of a single person (or brothers in the case of Nutshell). Reading them, I&amp;#39;ve often wanted to give present a different point of view - or alternatively, to give a hearty &amp;quot;hear, hear.&amp;quot; I believe that a book giving guidance would benefit greatly from being more of a conversation: where the authors all agree on something, that&amp;#39;s great; where they differ, it would be good to hear about the pros and cons of various approaches. The reader can then weigh up those factors as they apply to each particular real-world scenario.&lt;/p&gt;  &lt;h2&gt;Scope&lt;/h2&gt;  &lt;p&gt;So what would such a book contain? Opinions will vary of course, but &lt;em&gt;I&lt;/em&gt; would like to see:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Effective ways of using language features such as lambda expressions, generic type inference (and indeed generics in general), optional parameters, named arguments and extension methods. Assume that the reader knows &lt;em&gt;roughly&lt;/em&gt; what C# does, but give some extra details around things like iterator blocks and anonymous functions.&lt;/li&gt;    &lt;li&gt;Guidance around class design (in a similar fashion to the FDG, but with more input from others in the community)&lt;/li&gt;    &lt;li&gt;Core framework topics (again, assume the basics are understood):&lt;/li&gt;    &lt;ul&gt;     &lt;li&gt;Resource management (disposal etc)&lt;/li&gt;      &lt;li&gt;Exceptions&lt;/li&gt;      &lt;li&gt;Collections (including LINQ fundamentals)&lt;/li&gt;      &lt;li&gt;Streams&lt;/li&gt;      &lt;li&gt;Text (including internationalization)&lt;/li&gt;      &lt;li&gt;Numeric types&lt;/li&gt;      &lt;li&gt;Time-related APIs&lt;/li&gt;      &lt;li&gt;Concurrency&lt;/li&gt;      &lt;li&gt;Contracts&lt;/li&gt;      &lt;li&gt;AppDomains&lt;/li&gt;      &lt;li&gt;Security&lt;/li&gt;      &lt;li&gt;Performance&lt;/li&gt;   &lt;/ul&gt; &lt;/ul&gt;  &lt;p&gt;I would prefer to avoid anything around the periphery of .NET (WPF, WinForms, ASP.NET, WCF) - I believe those are better handled in different topics.&lt;/p&gt;  &lt;h2&gt;Obstacles and format&lt;/h2&gt;  &lt;p&gt;There&amp;#39;s one big problem with this idea, but I think it may be a saving grace too. Many of the leading authors work for different publishers. Clearly no single publisher is going to attract &lt;em&gt;all&lt;/em&gt; the best minds in the C# and .NET world. So how could this work in practice? Well...&lt;/p&gt;  &lt;p&gt;Imagine a web site for the book, paid for jointly by all interested publishers. The web site would be the foremost delivery mechanism for the content, both to browse and probably to download in formats appropriate for offline reading (PDF etc). The content would be edited in a collaborative style obviously, but exactly how that would work is a detail to be thrashed out. If you&amp;#39;ve read the annotated C# or CLI specifications, they have about the right feel - opinions can be attributed in places, but not &lt;em&gt;everything&lt;/em&gt; has a label.&lt;/p&gt;  &lt;p&gt;Any contributing publisher could &lt;em&gt;also&lt;/em&gt; take the material and publish it as hard copy if they so wished. Quite how this would work - with potentially multiple hard copy editions of the same content - would be interesting to see. There&amp;#39;s another reason against hard copy ever appearing though, which is that it would be immovable. I&amp;#39;d like to see this work evolve as new features appear and as more best practices are discovered. Publishers could monetize the web site via adverts, possibly according to how much they&amp;#39;re kicking into the site.&lt;/p&gt;  &lt;p&gt;I don&amp;#39;t know how the authors would get paid, admittedly, and that&amp;#39;s another problem. Would this cannibalize the sales of the books listed earlier? It wouldn&amp;#39;t make them redundant - certainly not for the Nutshell type of book, which teaches the basics as well as giving guidance. It would hit Effective C# harder, I suspect - and I apologise to Bill Wagner in advance; if this ever takes off and it hurts his bottom line, I&amp;#39;m very sorry - I think it&amp;#39;s in a good cause though.&lt;/p&gt;  &lt;h2&gt;Dream Team&lt;/h2&gt;  &lt;p&gt;So who would contribute to this? Part of me would like to say &amp;quot;anyone and everyone&amp;quot; in a Wikipedia kind of approach - but I think that practically, it makes sense for industry experts to take their places. (A good feedback/comments mechanism for anyone to use would be crucial, however.) Here&amp;#39;s a list which isn&amp;#39;t meant to be exhaustive, but would make me happy - please don&amp;#39;t take offence if your name isn&amp;#39;t on here but should be, and I wouldn&amp;#39;t expect &lt;em&gt;all&lt;/em&gt; of these people to be interested anyway.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Anders Hejlsberg&lt;/li&gt;    &lt;li&gt;Eric Lippert&lt;/li&gt;    &lt;li&gt;Mads Torgersen&lt;/li&gt;    &lt;li&gt;Don Box&lt;/li&gt;    &lt;li&gt;Brad Abrams&lt;/li&gt;    &lt;li&gt;Krzysztof Cwalina&lt;/li&gt;    &lt;li&gt;Joe Duffy&lt;/li&gt;    &lt;li&gt;Vance Morrison&lt;/li&gt;    &lt;li&gt;Rico Mariani&lt;/li&gt;    &lt;li&gt;Erik Meijer&lt;/li&gt;    &lt;li&gt;Don Symes&lt;/li&gt;    &lt;li&gt;Wes Dyer&lt;/li&gt;    &lt;li&gt;Jeff Richter&lt;/li&gt;    &lt;li&gt;Joe and Ben Albahari&lt;/li&gt;    &lt;li&gt;Andrew Troelsen&lt;/li&gt;    &lt;li&gt;Bill Wagner&lt;/li&gt;    &lt;li&gt;Trey Nash&lt;/li&gt;    &lt;li&gt;Mark Michaelis&lt;/li&gt;    &lt;li&gt;Jon Skeet (yeah, I want to contribute if I can)&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I imagine &amp;quot;principal&amp;quot; authors for specific topics (e.g. Joe Duffy for concurrency) but with all the authors dropping in comments in other places too.&lt;/p&gt;  &lt;h2&gt;Dream or reality?&lt;/h2&gt;  &lt;p&gt;I have no idea whether this will ever happen or not. I&amp;#39;d dearly love it to, and I&amp;#39;ve spoken to a few people before today who&amp;#39;ve been encouraging about the idea. I haven&amp;#39;t been putting any work into getting it off the ground - don&amp;#39;t worry, it&amp;#39;s not been delaying the second edition of C# in Depth. One day though, one day...&lt;/p&gt;  &lt;p&gt;Am I being hopelessly naïve to even consider such a venture? Is the scope too broad? Is the content valuable but not money-making? We&amp;#39;ll see.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1716905" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Books/default.aspx">Books</category></item><item><title>Faking COM to fool the C# compiler</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/07/07/faking-com-to-fool-the-c-compiler.aspx</link><pubDate>Tue, 07 Jul 2009 22:28:46 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1698645</guid><dc:creator>skeet</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1698645</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1698645</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/07/07/faking-com-to-fool-the-c-compiler.aspx#comments</comments><description>&lt;p&gt;C# 4 has some great features to make programming against COM components &lt;strike&gt;bearable&lt;/strike&gt; fun and exciting. In particular:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;PIA linking allows you to embed just the relevant bits of the Primary Interop Assembly into your own assembly, so the PIA isn&amp;#39;t actually required at execution time &lt;/li&gt;    &lt;li&gt;Named arguments and optional parameters make life &lt;em&gt;much&lt;/em&gt; simpler for APIs like Office which are full of methods with gazillions of parameters &lt;/li&gt;    &lt;li&gt;&amp;quot;ref&amp;quot; removal allows you to pass an argument by value even though the parameter is a by-reference parameter (COM only, folks - don&amp;#39;t worry!) &lt;/li&gt;    &lt;li&gt;Dynamic typing allows you to remove a load of casts by converting every parameter and return type of &amp;quot;object&amp;quot; into &amp;quot;dynamic&amp;quot; (if you&amp;#39;re using PIA linking) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I&amp;#39;m currently writing about these features for &lt;a href="http://manning.com/skeet2"&gt;the book&lt;/a&gt; (don&amp;#39;t forget to &lt;a href="http://msmvps.com/blogs/jon_skeet/archive/2009/07/06/books-going-cheap.aspx"&gt;buy it cheap on Friday&lt;/a&gt;) but I&amp;#39;m not really a COM person. I want to be able to see these compiler features at work against a really simple type. Unfortunately, these really are COM-specific features... so we&amp;#39;re going to have to persuade COM that the type really is a COM type.&lt;/p&gt;  &lt;p&gt;I got slightly stuck on this first, but thanks to &lt;a href="http://stackoverflow.com/questions/1093536"&gt;the power of Stack Overflow&lt;/a&gt;, I now have a reasonably complete demo &amp;quot;fake&amp;quot; COM type. It doesn&amp;#39;t do a lot, and in particular it doesn&amp;#39;t have any events, but it&amp;#39;s enough to show the compiler features:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;     &lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Runtime.InteropServices;     &lt;br /&gt;    &lt;br /&gt;&lt;span class="InlineComment"&gt;// Required for linking into another assembly (C# 4)&lt;/span&gt;     &lt;br /&gt;[assembly:Guid(&lt;span class="String"&gt;&amp;quot;86ca55e4-9d4b-462b-8ec8-b62e993aeb64&amp;quot;&lt;/span&gt;)]     &lt;br /&gt;[assembly:ImportedFromTypeLib(&lt;span class="String"&gt;&amp;quot;fake.tlb&amp;quot;&lt;/span&gt;)]     &lt;br /&gt;    &lt;br /&gt;&lt;span class="Namespace"&gt;namespace&lt;/span&gt; FakeCom     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [Guid(&lt;span class="String"&gt;&amp;quot;c3cb8098-0b8f-4a9a-9772-788d340d6ae0&amp;quot;&lt;/span&gt;)]     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [ComImport, CoClass(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(FakeImpl))]     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; FakeComponent     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;object&lt;/span&gt; MakeMeDynamic(&lt;span class="ReferenceType"&gt;object&lt;/span&gt; arg);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;void&lt;/span&gt; Foo([Optional] &lt;span class="MethodParameter"&gt;ref&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; x,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; [Optional] &lt;span class="MethodParameter"&gt;ref&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; y);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [Guid(&lt;span class="String"&gt;&amp;quot;734e6105-a20f-4748-a7de-2c83d7e91b04&amp;quot;&lt;/span&gt;)]     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; FakeImpl {}     &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;We have an interface representing our COM type, and a class which the interface claims will implement it. Fortunately the compiler doesn&amp;#39;t actually check that, so we can get away with leaving it entirely unimplemented. It&amp;#39;s also worth noting that our optional parameters can be by-reference parameters (which you can&amp;#39;t normally do in C# 4) and we haven&amp;#39;t given them any default values (as those are ignored for COM anyway).&lt;/p&gt;  &lt;p&gt;This is compiled just like any other assembly: &lt;/p&gt;  &lt;div class="code"&gt;csc /target:library FakeCom.cs &lt;/div&gt;  &lt;p&gt;Then we get to use it with a test program: &lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; FakeCom;    &lt;br /&gt;    &lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Test    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Yes, that is calling a &amp;quot;constructor&amp;quot; on an interface&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; FakeComponent com = &lt;span class="Keyword"&gt;new&lt;/span&gt; FakeComponent();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// The boring old fashioned way of calling a method&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; i = 0;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; j = &lt;span class="Keyword"&gt;null&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; com.Foo(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; i, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt; j);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Look ma, no ref!&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; com.Foo(10, &lt;span class="String"&gt;&amp;quot;Wow!&amp;quot;&lt;/span&gt;);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Who cares about parameter ordering?&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; com.Foo(y: &lt;span class="String"&gt;&amp;quot;Not me&amp;quot;&lt;/span&gt;, x: 0);    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// And the parameters are optional too&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; com.Foo();    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// The line below only works when linked rather than&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// referenced, as otherwise you need a cast.&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// The compiler treats it as if it both takes and&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// returns a dynamic value.&lt;/span&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; value = com.MakeMeDynamic(10);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;This is compiled either in the old &amp;quot;deploy the PIA as well&amp;quot; way (after adding a cast in the last line): &lt;/p&gt;  &lt;div class="code"&gt;csc /r:FakeCom.dll Test.cs &lt;/div&gt;  &lt;p&gt;... or by linking the PIA instead:&lt;/p&gt;  &lt;div class="code"&gt;csc /l:FakeCom.dll Test.cs &lt;/div&gt;  &lt;p&gt;(The difference is just using &lt;code&gt;/l&lt;/code&gt; instead of &lt;code&gt;/r&lt;/code&gt;.)&lt;/p&gt;  &lt;p&gt;When the test code is compiled as a reference, it decompiles in Reflector to this (I&amp;#39;ve added whitespace for clarity):&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; FakeComponent component = (FakeComponent) &lt;span class="Keyword"&gt;new&lt;/span&gt; FakeImpl();    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; x = 0;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; y = &lt;span class="Keyword"&gt;null&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; component.Foo(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; x, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt; y);    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; num2 = 10;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; str3 = &lt;span class="String"&gt;&amp;quot;Wow!&amp;quot;&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; component.Foo(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; num2, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt; str3);    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; str4 = &lt;span class="String"&gt;&amp;quot;Not me&amp;quot;&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; num3 = 0;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; component.Foo(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; num3, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt; str4);    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;int&lt;/span&gt; num4 = 0;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; str5 = &lt;span class="Keyword"&gt;null&lt;/span&gt;;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; component.Foo(&lt;span class="MethodParameter"&gt;ref&lt;/span&gt; num4, &lt;span class="MethodParameter"&gt;ref&lt;/span&gt; str5);    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; str2 = (&lt;span class="ReferenceType"&gt;string&lt;/span&gt;) component.MakeMeDynamic(10);    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;Note how the compiler has created local variables to pass by reference; any changes to the parameter are ignored when the method returns. (If you actually pass a variable by reference, the compiler won&amp;#39;t take that away, however.) &lt;/p&gt;  &lt;p&gt;When the code is linked instead, the middle section is the same, but the construction and the line calling &lt;code&gt;MakeMeDynamic&lt;/code&gt; are very different:&lt;/p&gt;  &lt;div class="code"&gt;&lt;span class="Modifier"&gt;private&lt;/span&gt;&amp;#160;&lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; FakeComponent component = (FakeComponent) Activator.CreateInstance(Type.GetTypeFromCLSID    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; (&lt;span class="Keyword"&gt;new&lt;/span&gt; Guid(&lt;span class="String"&gt;&amp;quot;734E6105-A20F-4748-A7DE-2C83D7E91B04&amp;quot;&lt;/span&gt;)));    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="InlineComment"&gt;// Middle bit as before&lt;/span&gt;    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="Statement"&gt;if&lt;/span&gt; (&amp;lt;Main&amp;gt;o__SiteContainer6.&amp;lt;&amp;gt;p__Site7 == &lt;span class="Keyword"&gt;null&lt;/span&gt;)    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;lt;Main&amp;gt;o__SiteContainer6.&amp;lt;&amp;gt;p__Site7 = CallSite&amp;lt;Func&amp;lt;CallSite, &lt;span class="ReferenceType"&gt;object&lt;/span&gt;, &lt;span class="ReferenceType"&gt;string&lt;/span&gt;&amp;gt;&amp;gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; .Create(&lt;span class="Keyword"&gt;new&lt;/span&gt; CSharpConvertBinder    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; (&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(&lt;span class="ReferenceType"&gt;string&lt;/span&gt;),&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; CSharpConversionKind.ImplicitConversion, &lt;span class="Keyword"&gt;false&lt;/span&gt;));    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;string&lt;/span&gt; str2 = &amp;lt;Main&amp;gt;o__SiteContainer6.&amp;lt;&amp;gt;p__Site7.Target.Invoke    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; (&amp;lt;Main&amp;gt;o__SiteContainer6.&amp;lt;&amp;gt;p__Site7, component.MakeMeDynamic(10));    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The interface is embedded in the generated assembly, but with a slightly different set of attributes:&lt;/p&gt;  &lt;div class="code"&gt;[ComImport, CompilerGenerated]   &lt;br /&gt;[Guid(&lt;span class="String"&gt;&amp;quot;C3CB8098-0B8F-4A9A-9772-788D340D6AE0&amp;quot;&lt;/span&gt;), TypeIdentifier]    &lt;br /&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; FakeComponent    &lt;br /&gt;{    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ReferenceType"&gt;object&lt;/span&gt; MakeMeDynamic(&lt;span class="ReferenceType"&gt;object&lt;/span&gt; arg);    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span class="ValueType"&gt;void&lt;/span&gt; Foo([Optional] &lt;span class="MethodParameter"&gt;ref&lt;/span&gt;&amp;#160;&lt;span class="ValueType"&gt;int&lt;/span&gt; x, [Optional] &lt;span class="MethodParameter"&gt;ref&lt;/span&gt;&amp;#160;&lt;span class="ReferenceType"&gt;string&lt;/span&gt; y);    &lt;br /&gt;} &lt;/div&gt;  &lt;p&gt;The class isn&amp;#39;t present at all.&lt;/p&gt;  &lt;p&gt;I should point out that doing this has no practical benefit in real code - but the ability to mess around with a pseudo-COM type rather than having to find a &lt;em&gt;real&lt;/em&gt; one with the exact members I want will make it a lot easier to try a few corner cases for the book.&lt;/p&gt;  &lt;p&gt;So, not a terribly productive evening in terms of getting actual writing done, but interesting nonetheless...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1698645" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Books/default.aspx">Books</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_+4/default.aspx">C# 4</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category></item><item><title>A different approach to inappropriate defaults</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/05/14/a-different-approach-to-inappropriate-defaults.aspx</link><pubDate>Thu, 14 May 2009 17:03:52 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1692419</guid><dc:creator>skeet</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1692419</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1692419</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/05/14/a-different-approach-to-inappropriate-defaults.aspx#comments</comments><description>&lt;p&gt;I&amp;#39;ve had a couple of bug reports about &lt;a href="http://code.google.com/p/protobuf-csharp-port/"&gt;my Protocol Buffers port&lt;/a&gt; - both nicely detailed, and one including a patch to fix it. (It&amp;#39;s only due to my lack of timeliness in actually submitting the change that the second bug report occurred. Oops.)&lt;/p&gt;  &lt;p&gt;The bug was in text formatting (although it also affected parsing). I was using the default &lt;code&gt;ToString&lt;/code&gt; behaviour for numbers, which meant that floats and doubles were being formatted as &amp;quot;50,15&amp;quot; in Germany instead of &amp;quot;50.15&amp;quot;. The unit tests caught this, but only if you ran them on a machine with an appropriate default culture.&lt;/p&gt;  &lt;p&gt;Aaargh. I&amp;#39;ve been struggling with a similar problem in a library I &lt;em&gt;can&amp;#39;t&lt;/em&gt; change, which uses the system default time zone for various calculations in Java. When you&amp;#39;re running server code, the default time zone is almost never the one you want to use, and it certainly isn&amp;#39;t in my case.&lt;/p&gt;  &lt;p&gt;A similar problem is Java&amp;#39;s decision to use the system default encoding in all kinds of bizarre places - &lt;code&gt;FileReader&lt;/code&gt; doesn&amp;#39;t even let you specify the encoding, which makes it almost entirely useless in my view.&lt;/p&gt;  &lt;p&gt;So I&amp;#39;ve been wondering how we could fix this and problems like it. One option is to completely remove the defaults. If you always &lt;em&gt;had&lt;/em&gt; to pass in a &lt;code&gt;CultureInfo&lt;/code&gt;/&lt;code&gt;Locale&lt;/code&gt;, &lt;code&gt;TimeZoneInfo&lt;/code&gt;/&lt;code&gt;TimeZone&lt;/code&gt;, &lt;code&gt;Encoding&lt;/code&gt;/&lt;code&gt;Charset&lt;/code&gt; when you call any method which might be culturally sensitive.&lt;/p&gt;  &lt;h3&gt;Making life easier (in .NET)&lt;/h3&gt;  &lt;p&gt;It strikes me that .NET has a useful abstraction here: the assembly as the unit of deployment. (Java&amp;#39;s closest equivalent is probably a jar file, which probably gets messier.)&lt;/p&gt;  &lt;p&gt;Within one assembly, I suspect in many cases you always want to make the same decision. For example, in protocol buffers I would like to use the invariant culture all the time. It would be nice if I could say that, and then get the right behaviour by default. Here are the options I&amp;#39;d like to be able to apply (for each of culture, time zone and character encoding - there may be others):&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Use a culture-neutral default (the invariant culture, UTF-8, UTC)&lt;/li&gt;    &lt;li&gt;Use a specific set of values (e.g. en-GB, Windows-1252, &amp;quot;Europe/London&amp;quot;)&lt;/li&gt;    &lt;li&gt;Use the system default values&lt;/li&gt;    &lt;li&gt;Use whatever the calling assembly is using&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Of course you should still have the option of specifying overrides on a per call basis, but I think this &lt;em&gt;might&lt;/em&gt; be a way forward.&lt;/p&gt;  &lt;p&gt;Thoughts? I realise it&amp;#39;s almost certainly too late for this to actually be implemented now, but would it have been a good idea? Or is it just an alternative source of confusion?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1692419" 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/Java/default.aspx">Java</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category></item><item><title>Breaking Liskov</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/03/16/breaking-liskov.aspx</link><pubDate>Mon, 16 Mar 2009 17:48:04 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1678395</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=1678395</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1678395</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/03/16/breaking-liskov.aspx#comments</comments><description>&lt;p&gt;Very recently, &lt;a href="http://news.bbc.co.uk/1/hi/technology/7937010.stm"&gt;Barbara Liskov won the Turing award&lt;/a&gt;, which makes it a highly appropriate time to ponder when it&amp;#39;s reasonable to ignore her most famous piece of work, the &lt;a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle"&gt;Liskov Substitution (or Substitutability) Principle&lt;/a&gt;. This is not idle speculation: I&amp;#39;ve had a feature request for &lt;a href="http://pobox.com/~skeet/csharp/miscutil"&gt;MiscUtil&lt;/a&gt;. The request makes sense, simplifies the code, and is good all round - but it breaks substitutability &lt;em&gt;and&lt;/em&gt; documented APIs.&lt;/p&gt; &lt;p&gt;The substitutability principle is in some ways just common sense. It says (in paraphrase) that if your code works for some base type T, it should be able to work with subtype of T, S. If it doesn&amp;#39;t, S is breaking substitutability. This principle is at the heart of inheritance and polymorphism - I should be able to use a Stream without knowing the details of what its underlying storage is, for example.&lt;/p&gt; &lt;p&gt;Liskov&amp;#39;s formulation is:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;i&gt;Let &lt;i&gt;q&lt;/i&gt;(&lt;i&gt;x&lt;/i&gt;) be a property provable about objects &lt;i&gt;x&lt;/i&gt; of type &lt;i&gt;T&lt;/i&gt;. Then &lt;i&gt;q&lt;/i&gt;(&lt;i&gt;y&lt;/i&gt;) should be true for objects &lt;i&gt;y&lt;/i&gt; of type &lt;i&gt;S&lt;/i&gt; where &lt;i&gt;S&lt;/i&gt; is a subtype of &lt;i&gt;T&lt;/i&gt;.&lt;/i&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;So, that&amp;#39;s the rule. Sounds like a good idea, right?&lt;/p&gt; &lt;h3&gt;Breaking BinaryReader&amp;#39;s contract&lt;/h3&gt; &lt;p&gt;My case in point is EndianBinaryReader (and EndianBinaryWriter, but the arguments will all be the same - it&amp;#39;s better to focus on a single type). This is simply an equivalent to &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx"&gt;System.IO.BinaryReader&lt;/a&gt;, but it lets you specify the endianness to use when converting values.&lt;/p&gt; &lt;p&gt;Currently, EndianBinaryReader is a completely separate class to BinaryReader. They have no inheritance relationship. However, as it happens, BinaryReader isn&amp;#39;t sealed, and all of the appropriate methods are virtual. So, can we make EndianBinaryReader derive from BinaryReader and use it as a drop-in replacement? Well... that&amp;#39;s where the trouble starts.&lt;/p&gt; &lt;p&gt;There&amp;#39;s no difficulty &lt;em&gt;technically&lt;/em&gt; in doing it. The implementation is fairly straightforward - indeed, it means we can drop a bunch of methods from EndianBinaryReader and let BinaryReader handle it instead. (This is particularly handy for text, which is fiddly to get right.) I currently have the code in another branch, and it works fine.&lt;/p&gt; &lt;h3&gt;And I would have gotten away with it if it weren&amp;#39;t for that pesky inheritance...&lt;/h3&gt; &lt;p&gt;The problem is whether or not it&amp;#39;s the right thing to do. To start with, it breaks Liskov&amp;#39;s substitutability principle, if the &amp;quot;property&amp;quot; we consider is &amp;quot;the result of calling ReadInt32 when the next four bytes of the underlying stream are 00, 00, 00, 01&amp;quot; for example. Not having read Liskov&amp;#39;s paper for myself (I really should, some time) I&amp;#39;m not sure whether this is the intended kind of use or not. More on that later.&lt;/p&gt; &lt;p&gt;The second problem is that it contradicts the documentation for BinaryReader. For example, the &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.readint32.aspx"&gt;docs for ReadInt32&lt;/a&gt; state: &amp;quot;&lt;a href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx"&gt;BinaryReader&lt;/a&gt; reads this data type in little-endian format.&amp;quot; That&amp;#39;s a tricky bit of documentation to understand precisely - it&amp;#39;s correct for BinaryReader itself, but does that mean it should be true for all subclasses too?&lt;/p&gt; &lt;p&gt;When I&amp;#39;ve written in various places about the problems of inheritance, and why if you design a class to be unsealed that means doing more design work, this is the kind of thing I&amp;#39;ve been talking about. How much detail does it make sense to specify here? How much leeway is there for classes overriding ReadInt32? Could a different implementation read a &amp;quot;compressed&amp;quot; Int32 instead of always reading four bytes, for example? Should the client care, if they make sure they&amp;#39;ve obtained an appropriate BinaryReader for their data source in the first place? This is basically the same as asking how strictly we should apply Liskov&amp;#39;s substitutability principle. If two types are the same in &lt;em&gt;every&lt;/em&gt; property, surely we can&amp;#39;t distinguish between them at all.&lt;/p&gt; &lt;p&gt;I wonder whether most design questions of inheritance basically boil down to defining which properties should obey Liskov&amp;#39;s substitutability principle and which needn&amp;#39;t, for the type you&amp;#39;re designing. Of course, it&amp;#39;s not just black and white - there will always be exceptions and awkward points. Programming is often about nuance, even if we might wish that not to be the case.&lt;/p&gt; &lt;h3&gt;Blow it, let&amp;#39;s do it anyway...&lt;/h3&gt; &lt;p&gt;Coming back to BinaryReader, I &lt;em&gt;think&lt;/em&gt; (unless I can be persuaded otherwise) that the benefits from going against the documentation (and strict substitutability) outweigh the downsides. In particular, BinaryReaders don&amp;#39;t tend to be passed around in my experience - the code which creates it is usually the code which uses it too, or it&amp;#39;s at least closely related. The risk of breaking code by passing it a BinaryReader using an unexpected endianness is therefore quite low, even though it&amp;#39;s theoretically possible.&lt;/p&gt; &lt;p&gt;So, am I miles off track? This is for a class library, after all - should I be more punctilious about playing by the rules? Or is pragmatism the more important principle here?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1678395" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/General/default.aspx">General</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category></item><item><title>Quick rant: why isn't there an Exception(string, params object[]) constructor?</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/01/23/quick-rant-why-isn-t-there-an-exception-string-params-object-constructor.aspx</link><pubDate>Fri, 23 Jan 2009 21:42:52 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1665160</guid><dc:creator>skeet</dc:creator><slash:comments>26</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1665160</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1665160</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/01/23/quick-rant-why-isn-t-there-an-exception-string-params-object-constructor.aspx#comments</comments><description>&lt;p&gt;This &lt;a href="http://stackoverflow.com/questions/474564"&gt;Stack Overflow question&lt;/a&gt; has reminded me of something I often wish existed in common exception constructors - an overload taking a format string and values. For instance, it would be really nice to be able to write:&lt;/p&gt; &lt;div class="code"&gt;&lt;span class="Statement"&gt;throw&lt;/span&gt;&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt; IOException(&lt;span class="String"&gt;&amp;quot;Expected to read {0} bytes but only {1} were available&amp;quot;&lt;/span&gt;,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; requiredSize, bytesRead); &lt;/div&gt; &lt;p&gt;Of course, with no way of explicitly inheriting constructors (which I almost always want for exceptions, and almost never want for anything else) it would mean yet another overload to copy and paste from another exception, but the times when I&amp;#39;ve actually written it in my own exceptions it&amp;#39;s been &lt;em&gt;hugely&lt;/em&gt; handy, particularly for tricky cases where you&amp;#39;ve got a lot of data to include in the message. (You&amp;#39;d also want an overload taking a nested exception first as well, adding to the baggage...)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1665160" width="1" height="1"&gt;</description><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/General/default.aspx">General</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Wacky+Ideas/default.aspx">Wacky Ideas</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/Stack+Overflow/default.aspx">Stack Overflow</category></item><item><title>Horrible grotty hack: returning an anonymous type instance</title><link>http://msmvps.com/blogs/jon_skeet/archive/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance.aspx</link><pubDate>Fri, 09 Jan 2009 07:52:14 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1659812</guid><dc:creator>skeet</dc:creator><slash:comments>21</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1659812</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1659812</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance.aspx#comments</comments><description>&lt;p&gt;One of the reasons I don&amp;#39;t view anonymous types as being too bad is that they&amp;#39;re nicely confined to methods. You can&amp;#39;t declare the type that you&amp;#39;re returning from a method if it&amp;#39;s anonymous (or if one of its type arguments is generic, e.g. a &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt; where &lt;code&gt;T&lt;/code&gt; is an anonymous type and &lt;code&gt;T&lt;/code&gt; isn&amp;#39;t a type parameter to the method itself). However, you &lt;em&gt;can&lt;/em&gt; get around this if you&amp;#39;re sneaky.&lt;/p&gt; &lt;p&gt;I&amp;#39;ve always known that it&amp;#39;s perfectly easy to return an instance of an anonymous type by declaring that the method will return &lt;code&gt;object&lt;/code&gt;. However, it hadn&amp;#39;t occurred to me before today that you can actually cast back to that type afterwards. Of course, you can&amp;#39;t just use a normal cast expression - that requires the name of the type to be known at compile-time. But you can do a cast in a generic method... and you can use type inference to supply a type argument... and two anonymous type instance creation expressions will use the same type within the same assembly if the order, names and types of the properties are the same.&lt;/p&gt; &lt;p&gt;Behold the evil cheesecake factory!&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="Modifier"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; GrottyHacks&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;internal&lt;/span&gt;&amp;nbsp;&lt;span class="Modifier"&gt;static&lt;/span&gt; T Cast&amp;lt;T&amp;gt;(&lt;span class="ReferenceType"&gt;object&lt;/span&gt; target, T example)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt; (T) target;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; CheesecakeFactory&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;object&lt;/span&gt; CreateCheesecake()&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Statement"&gt;return&lt;/span&gt;&amp;nbsp;&lt;span class="Keyword"&gt;new&lt;/span&gt; { Fruit=&lt;span class="String"&gt;&amp;quot;Strawberry&amp;quot;&lt;/span&gt;, Topping=&lt;span class="String"&gt;&amp;quot;Chocolate&amp;quot;&lt;/span&gt; };&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;void&lt;/span&gt; Main()&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ReferenceType"&gt;object&lt;/span&gt; weaklyTyped = CreateCheesecake();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Linq"&gt;var&lt;/span&gt; stronglyTyped = GrottyHacks.Cast(weaklyTyped,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Keyword"&gt;new&lt;/span&gt; { Fruit=&lt;span class="String"&gt;&amp;quot;&amp;quot;&lt;/span&gt;, Topping=&lt;span class="String"&gt;&amp;quot;&amp;quot;&lt;/span&gt; });&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Cheesecake: {0} ({1})&amp;quot;&lt;/span&gt;,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; stronglyTyped.Fruit, stronglyTyped.Topping);&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;} &lt;/div&gt; &lt;p&gt;The important thing to note here is that the &lt;code&gt;stronglyTyped&lt;/code&gt; variable really is of the same anonymous type as the one used in the &lt;code&gt;CreateCheesecake&lt;/code&gt; method. When we use the &lt;code&gt;Fruit&lt;/code&gt; and &lt;code&gt;Topping&lt;/code&gt; properties in the last statement, that&amp;#39;s checked at compile-time.&lt;/p&gt; &lt;p&gt;Of course, it all goes pear-shaped if you make the slightest of errors when giving the &lt;code&gt;Cast&lt;/code&gt; method an example of what you want to cast to - if you got the order of the properties wrong, for example, the code would still compile, but the cast would throw an exception at execution time.&lt;/p&gt; &lt;p&gt;How useful is this? Ooh, probably not at all. &lt;strong&gt;Please do not use this &amp;quot;technique&amp;quot; in your code. If you do, at least don&amp;#39;t mention my name anywhere near it.&lt;/strong&gt; It&amp;#39;s all fun though, 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=1659812" 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></item><item><title>Value types and parameterless constructors</title><link>http://msmvps.com/blogs/jon_skeet/archive/2008/12/10/value-types-and-parameterless-constructors.aspx</link><pubDate>Wed, 10 Dec 2008 17:55:40 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1656405</guid><dc:creator>skeet</dc:creator><slash:comments>11</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1656405</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1656405</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2008/12/10/value-types-and-parameterless-constructors.aspx#comments</comments><description>&lt;p&gt;There have been a couple of questions on StackOverflow about value types and parameterless constructors:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://stackoverflow.com/questions/203695"&gt;Structure vs Class in C#&lt;/a&gt;  &lt;li&gt;&lt;a href="http://stackoverflow.com/questions/333829"&gt;Why can’t I define a default constructor for a struct in .NET&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;I learned quite a bit when answering both of these. When a &lt;a href="http://stackoverflow.com/questions/354136"&gt;further question&lt;/a&gt; about the default value of a type (particularly with respect to generics) came up, I thought it would be worth delving into a bit more depth. Very little of this is actually relevant most of the time, but it&amp;#39;s interesting nonetheless.&lt;/p&gt; &lt;p&gt;I won&amp;#39;t go over most of the details I discovered in &lt;a href="http://stackoverflow.com/questions/203695/structure-vs-class-in-c#204009"&gt;my answer to the first question&lt;/a&gt;,&amp;nbsp; but if you&amp;#39;re interested in the IL generated by the statement &amp;quot;x = new Guid();&amp;quot; then have a look there for more details.&lt;/p&gt; &lt;p&gt;Let&amp;#39;s start off with the first and most important thing I&amp;#39;ve learned about value types recently:&lt;/p&gt; &lt;h3&gt;Yes, you &lt;em&gt;can&lt;/em&gt; write a parameterless constructor for a value type in .NET&lt;/h3&gt; &lt;p&gt;I very carefully wrote &amp;quot;in .NET&amp;quot; there - &amp;quot;in C#&amp;quot; would have been incorrect. I had always believed that the CLI spec prohibited value types from having parameterless constructors. (The C# spec used the terminology in a slightly different way - it treats &lt;em&gt;all&lt;/em&gt; value types as having a parameterless constructor. This makes the language more consistent for the most part, but it does give rise to some interesting behaviour which we&amp;#39;ll see later on.)&lt;/p&gt; &lt;p&gt;It turns out that if you write your value type in IL, you can provide your own parameterless constructor with custom code without ilasm complaining at all. It&amp;#39;s possible that other languages targeting the CLI allow you to do this as well, but as I don&amp;#39;t know any, I&amp;#39;ll stick to IL. Unfortunately I don&amp;#39;t know IL terribly well, so I thought I&amp;#39;d just start off with some C# and go from there:&lt;/p&gt; &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;struct&lt;/span&gt; Oddity&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;public&lt;/span&gt; Oddity(&lt;span class="ValueType"&gt;int&lt;/span&gt; removeMe)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; System.Console.WriteLine(&lt;span class="String"&gt;&amp;quot;Oddity constructor called&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;} &lt;/div&gt; &lt;p&gt;I compiled that into its own class library, and then disassembled it with &lt;code&gt;ildasm /out:Oddity.il Oddity.dll&lt;/code&gt;. After changing the constructor to be parameterless, removing a few comments, and removing some compiler-generated assembly attributes) I ended up with this IL:&lt;/p&gt;&lt;pre&gt;.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )  
  .ver 2:0:0:0
}
.assembly Oddity
{
  .hash algorithm 0x00008004
  .ver 0:0:0:0
}
.module Oddity.dll
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003
.corflags 0x00000001

.class public sequential ansi sealed beforefieldinit Oddity
       extends [mscorlib]System.ValueType
{
  .pack 0
  .size 1
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      &amp;quot;Oddity constructor called&amp;quot;
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  }
}
&lt;/pre&gt;
&lt;p&gt;I reassembled this with &lt;code&gt;ilasm /dll /out:Oddity.dll Oddity.il&lt;/code&gt;. So far, so good. We have a value type with a custom constructor in a class library. It doesn&amp;#39;t do anything particularly clever - it just logs that it&amp;#39;s been called. That&amp;#39;s enough for our test program.&lt;/p&gt;
&lt;h2&gt;When does the parameterless constructor get called?&lt;/h2&gt;
&lt;p&gt;There are various things one &lt;i&gt;could&lt;/i&gt; investigate about parameterless constructors, but I&amp;#39;m mostly interested in when they get called. The test application is reasonably simple, but contains lots of cases - each writes to the console what it&amp;#39;s about to do, then does something which &lt;i&gt;might&lt;/i&gt; call the constructor. Without further ado:&lt;/p&gt;
&lt;div class="code"&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System;&lt;br /&gt;&lt;span class="Namespace"&gt;using&lt;/span&gt; System.Runtime.CompilerServices;&lt;br /&gt;&lt;br /&gt;&lt;span class="ReferenceType"&gt;class&lt;/span&gt; Test&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;static&lt;/span&gt; Oddity staticField;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Oddity instanceField;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&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; Main()&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;Declaring local variable&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Oddity localDeclarationOnly;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="InlineComment"&gt;// No variables within the value, so we can use it&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="InlineComment"&gt;// without inializing anything&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;Boxing&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ReferenceType"&gt;object&lt;/span&gt; o = localDeclarationOnly;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="InlineComment"&gt;// Just make sure it&amp;#39;s really done it&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(o.ToString());&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;new Oddity() - set local variable&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Oddity local = &lt;span class="Keyword"&gt;new&lt;/span&gt; Oddity();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;Create instance of Test - contains instance variable&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Test t = &lt;span class="Keyword"&gt;new&lt;/span&gt; Test();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;new Oddity() - set instance field&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; t.instanceField = &lt;span class="Keyword"&gt;new&lt;/span&gt; Oddity();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;new Oddity() - set static field&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; staticField = &lt;span class="Keyword"&gt;new&lt;/span&gt; Oddity();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;new Oddity[10]&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; o = &lt;span class="Keyword"&gt;new&lt;/span&gt; Oddity[10];&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;Passing argument to method&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; MethodWithParameter(local);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; GenericMethod&amp;lt;Oddity&amp;gt;();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; GenericMethod2&amp;lt;Oddity&amp;gt;();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;Activator.CreateInstance(typeof(Oddity))&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Activator.CreateInstance(&lt;span class="Keyword"&gt;typeof&lt;/span&gt;(Oddity));&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;Activator.CreateInstance&amp;lt;Oddity&amp;gt;()&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Activator.CreateInstance&amp;lt;Oddity&amp;gt;();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; [MethodImpl(MethodImplOptions.NoInlining)]&lt;br /&gt;&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; MethodWithParameter(Oddity oddity)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="InlineComment"&gt;// No need to do anything&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;void&lt;/span&gt; GenericMethod&amp;lt;T&amp;gt;() &lt;span class="Linq"&gt;where&lt;/span&gt; T : &lt;span class="Keyword"&gt;new&lt;/span&gt;()&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;default(T) in generic method with new() constraint&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; T t = &lt;span class="Modifier"&gt;default&lt;/span&gt;(T);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;new T() in generic method with new() constraint&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; t = &lt;span class="Keyword"&gt;new&lt;/span&gt; T();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;void&lt;/span&gt; GenericMethod2&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;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;default(T) in generic method with struct constraint&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; T t = &lt;span class="Modifier"&gt;default&lt;/span&gt;(T);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Report(&lt;span class="String"&gt;&amp;quot;new T() in generic method with struct constraint&amp;quot;&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; t = &lt;span class="Keyword"&gt;new&lt;/span&gt; T();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="Modifier"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span class="ValueType"&gt;void&lt;/span&gt; Report(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; text)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(text);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;} &lt;/div&gt;
&lt;p&gt;And here are the results:&lt;/p&gt;
&lt;div class="output"&gt;Declaring local variable&lt;br /&gt;Boxing&lt;br /&gt;Oddity&lt;br /&gt;new Oddity() - set local variable&lt;br /&gt;Oddity constructor called&lt;br /&gt;Create instance of Test - contains instance variable&lt;br /&gt;new Oddity() - set instance field&lt;br /&gt;Oddity constructor called&lt;br /&gt;new Oddity() - set static field&lt;br /&gt;Oddity constructor called&lt;br /&gt;new Oddity[10]&lt;br /&gt;Passing argument to method&lt;br /&gt;default(T) in generic method with new() constraint&lt;br /&gt;new T() in generic method with new() constraint&lt;br /&gt;default(T) in generic method with struct constraint&lt;br /&gt;new T() in generic method with struct constraint&lt;br /&gt;Activator.CreateInstance(typeof(Oddity))&lt;br /&gt;Oddity constructor called&lt;br /&gt;Activator.CreateInstance&amp;lt;Oddity&amp;gt;()&lt;br /&gt;Oddity constructor called &lt;/div&gt;
&lt;p&gt;So, to split these out: &lt;/p&gt;
&lt;h2&gt;Operations which &lt;i&gt;do&lt;/i&gt; call the constructor&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;new Oddity() - whatever we&amp;#39;re storing the result in. This isn&amp;#39;t much of a surprise. What may surprise you is that it gets called even if you compile Test.cs against the original Oddity.dll (without the custom parameterless constructor) and then just rebuild Oddity.dll. 
&lt;li&gt;&lt;code&gt;Activator.CreateInstance&amp;lt;T&amp;gt;()&lt;/code&gt; and &lt;code&gt;Activator.CreateInstance(Type)&lt;/code&gt;. I wouldn&amp;#39;t be particular surprised by this either way. &lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt;Operations which &lt;i&gt;don&amp;#39;t&lt;/i&gt; call the constructor&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Just declaring a variable, whether local, static or instance 
&lt;li&gt;Boxing 
&lt;li&gt;Creating an array - good job, as this could be a real performance killer 
&lt;li&gt;Using &lt;code&gt;default(T) in a generic method - this one didn&amp;#39;t surprise me&lt;/code&gt; 
&lt;li&gt;Using &lt;code&gt;new T()&lt;/code&gt; in a generic method - this one really &lt;i&gt;did&lt;/i&gt; surprise me. Not only is it counterintuitive, but in IL it just calls &lt;code&gt;Activator.CreateInstance&amp;lt;T&amp;gt;()&lt;/code&gt;. What&amp;#39;s the difference between this and calling &lt;code&gt;Activator.CreateInstance&amp;lt;Oddity&amp;gt;()&lt;/code&gt;? I really don&amp;#39;t understand.&lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt;Conclusions&lt;/h2&gt;
&lt;p&gt;Well, I&amp;#39;m still glad that C# doesn&amp;#39;t let us define our own parameterless constructors for value types, given the behaviour. The main reason for using it - as far as I&amp;#39;ve seen - it to make sure that the &amp;quot;default value&amp;quot; for a type is sensible. Given that it&amp;#39;s possible to get a usable value of the type without the constructor being called, this wouldn&amp;#39;t work anyway. Writing such a constructor would be like making a value type mutable - almost always a bad idea.&lt;/p&gt;
&lt;p&gt;However, it&amp;#39;s nice to know it&amp;#39;s &lt;em&gt;possible&lt;/em&gt;, just on the grounds that learning new things is always a good thing. And at least next time someone asks a similar question, I&amp;#39;ll have somewhere to point them...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1656405" 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/CSharpDevCenter/default.aspx">CSharpDevCenter</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/CSharpDev/default.aspx">CSharpDev</category></item><item><title>Redesigning System.Object/java.lang.Object</title><link>http://msmvps.com/blogs/jon_skeet/archive/2008/12/05/redesigning-system-object-java-lang-object.aspx</link><pubDate>Fri, 05 Dec 2008 17:52:44 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1655908</guid><dc:creator>skeet</dc:creator><slash:comments>31</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1655908</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1655908</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2008/12/05/redesigning-system-object-java-lang-object.aspx#comments</comments><description>&lt;p&gt;I&amp;#39;ve had quite a few discussions with a colleague about some failures of Java and .NET. The issue we keep coming back to is the root of the inheritance tree. There&amp;#39;s no doubt in my mind that &lt;em&gt;having&lt;/em&gt; a tree with a single top-level class is a good thing, but it&amp;#39;s grown a bit too big for its boots.&lt;/p&gt; &lt;p&gt;Pretty much everything in this post applies to both .NET and Java, sometimes with a few small changes. Where it might be unclear, I&amp;#39;ll point out the changes explicitly - otherwise I&amp;#39;ll just use the .NET terminology.&lt;/p&gt; &lt;h3&gt;What&amp;#39;s in &lt;a href="http://msdn.microsoft.com/en-us/library/system.object.aspx"&gt;System.Object&lt;/a&gt;?&lt;/h3&gt; &lt;p&gt;Before we work out what we might be able to change, let&amp;#39;s look at what we&amp;#39;ve got. I&amp;#39;m only talking about instance methods. At the moment:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;A &lt;a href="http://msdn.microsoft.com/en-us/library/system.object.object.aspx"&gt;parameterless constructor&lt;/a&gt;  &lt;li&gt;A &lt;a href="http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx"&gt;finalizer&lt;/a&gt;  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx"&gt;GetType()&lt;/a&gt;  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx"&gt;GetHashCode()&lt;/a&gt;  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.object.equals.aspx"&gt;Equals(Object)&lt;/a&gt;  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx"&gt;ToString()&lt;/a&gt;  &lt;li&gt;(&lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.wait.aspx"&gt;Monitor.Wait&lt;/a&gt;)  &lt;li&gt;(&lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx"&gt;Monitor.Pulse&lt;/a&gt;)  &lt;li&gt;(&lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulseall.aspx"&gt;Monitor.PulseAll&lt;/a&gt;)  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx"&gt;MemberwiseClone&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;h3&gt;Life-cycle and type identity&lt;/h3&gt; &lt;p&gt;There are three members which I believe really need to be left alone.&lt;/p&gt; &lt;p&gt;We need a parameterless constructor because (at least with the current system of chaining constructors to each other) we have to have &lt;em&gt;some&lt;/em&gt; constructor, and I can&amp;#39;t imagine what parameter we might want to give it. I certainly find it hard to believe there&amp;#39;s a particular piece of state which really deserves to be a part of &lt;em&gt;every&lt;/em&gt; object but which we&amp;#39;re currently missing.&lt;/p&gt; &lt;p&gt;I really don&amp;#39;t care that much about finalizers. Should the finalizer be part of Object itself, or should it just get handled automatically by the CLR if and only if it&amp;#39;s defined somewhere in the inheritance chain? Frankly, who cares. No doubt it makes a big difference to the implementation somewhere, but that&amp;#39;s not my problem. All I care about when it comes to finalizers is that when I have to write them it&amp;#39;s as easy as possible to do it properly, and that I don&amp;#39;t have to write them very often in the first place. (With &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx"&gt;SafeHandle&lt;/a&gt;, it should be a pretty rare occurrence in .NET, even when you&amp;#39;re dealing directly with unmanaged resources.)&lt;/p&gt; &lt;p&gt;GetType() or (getClass() in Java) is pretty important. I can&amp;#39;t see any particular alternative to having this within Object, unless you make it a static method somewhere else with an Object parameter. In fact, that would have the advantage of freeing up the name for use within your own classes. The functionality is sufficiently important (and really does apply to every object) that I think it&amp;#39;s worth keeping.&lt;/p&gt; &lt;h3&gt;Comparison methods&lt;/h3&gt; &lt;p&gt;Okay, time to get controversial. I don&amp;#39;t think every object should have to be able to compare itself with another object. Of course, most types don&amp;#39;t really support this anyway - we just end up with reference equality by default.&lt;/p&gt; &lt;p&gt;The trouble with comparisons is that everyone&amp;#39;s got a different idea of what makes something equal. There are some types where it really is obvious - there&amp;#39;s only one natural comparison. Integers spring to mind. There are other types which have multiple natural equality comparisons - floating point numbers (exact, within an absolute epsilon, and within a relative epsilon) and strings (ordinal, culture sensitive and/or case sensitive) are examples of this. Then there are composite types where you may or may not care about certain aspects - when comparing URLs, do I care about case? Do I care about fragments? For http, if the port number is explicitly specified as 80, is that different to a URL which is still http but leaves the port number implicit?&lt;/p&gt; &lt;p&gt;.NET represents these reasonably well already, with the &lt;a href="http://msdn.microsoft.com/en-us/library/ms131187.aspx"&gt;IEquatable&amp;lt;T&amp;gt;&lt;/a&gt; interface saying &amp;quot;I know how to compare myself with an instance of type T, and how to produce a hashcode for myself&amp;quot; and &lt;a href="http://msdn.microsoft.com/en-us/library/ms132151.aspx"&gt;IEqualityComparer&amp;lt;T&amp;gt;&lt;/a&gt; interface saying &amp;quot;I know how to compare two instances of T, and how to produce a hashcode for one instance of T.&amp;quot; Now suppose we didn&amp;#39;t have the (nongeneric!) Equals() method and GetHashCode() in System.Object. Any type which had a natural equality comparison would still let you compare it for equality by implementing IEquatable&amp;lt;T&amp;gt;.Equals - but anything else would either force you to use reference equality or an implementation of IEqualityComparer&amp;lt;T&amp;gt;.&lt;/p&gt; &lt;p&gt;Some of the principle consumers of equality comparisons are collections - particularly dictionaries (which is why it&amp;#39;s so important that the interfaces should include hashcode generation). With the current way that .NET generics work, it would be tricky to have a constraint on a &lt;em&gt;constructor&lt;/em&gt; such that if you only specified the types, it would only work if the key type implemented IEquatable&amp;lt;T&amp;gt;, but it&amp;#39;s easy enough to do with static methods (on a non-generic type). Alternatively you could specify any type and an appropriate IEqualityComparer&amp;lt;T&amp;gt; to use for the keys. We&amp;#39;d need an IdentityComparer&amp;lt;T&amp;gt; to work just with references (and provide the equivalent functionaliy to Object.GetHashCode) but that&amp;#39;s not hard - and it would be &lt;em&gt;absolutely&lt;/em&gt; obvious what the comparison was when you built the dictionary.&lt;/p&gt; &lt;h3&gt;Monitors and threading&lt;/h3&gt; &lt;p&gt;This is possibly my biggest gripe. The fact that every object has a monitor associated with it was a mistake in Java, and was unfortunately copied in .NET. This promotes the bad practice of locking on &amp;quot;this&amp;quot; and on types - both of which are typically publicly accessible references. I believe that unless a reference is exposed explicitly for the purpose of locking (like &lt;a href="http://msdn.microsoft.com/en-us/library/system.collections.icollection.syncroot.aspx"&gt;ICollection.SyncRoot&lt;/a&gt;) then you should avoid locking on any reference which other code knows about. I typically have a private read-only variable for locking purposes. If you&amp;#39;re following these guidelines, it makes no sense to be able to lock on absolutely any reference - it would be better to make the Monitor class instantiable, and make Wait/Pulse/PulseAll instance members. (In Java this would mean creating a new class and moving Object.wait/notify/notifyAll members to that class.)&lt;/p&gt; &lt;p&gt;This would lead to cleaner, more readable code in my view. I&amp;#39;d also do away with the &amp;quot;lock&amp;quot; statement in C#, making Monitor.Enter return a token implementing IDisposable - so &amp;quot;using&amp;quot; statements would replace locks, freeing up a keyword &lt;em&gt;and&lt;/em&gt; giving the flexibility of having multiple overloads of Monitor.Enter. Arguably if one were redesigning all of this anyway, it would be worth looking at whether or not monitors should really be reentrant. Any time you &lt;em&gt;use&lt;/em&gt; lock reentrancy, you&amp;#39;re probably not thinking hard enough about the design. Now there&amp;#39;s a nice overgeneralisation with which to end this section...&lt;/p&gt; &lt;h3&gt;String representations&lt;/h3&gt; &lt;p&gt;This is an interesting one. I&amp;#39;m genuinely on the fence here. I find ToString() (and the fact that it&amp;#39;s called implicitly in many circumstances) hugely useful, but it feels like it&amp;#39;s attempting to satisfy three different goals:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Giving a developer-readable representation when logging and debugging&lt;/li&gt; &lt;li&gt;Giving a user-readable representation as part of a formatted message in a UI&lt;/li&gt; &lt;li&gt;Giving a machine-readable format (although this is relatively rare for anything other than numeric types)&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;It&amp;#39;s interesting to note that Java and .NET differ as to which of these to use for numbers - Java plumps for &amp;quot;machine-readable&amp;quot; and .NET goes for &amp;quot;human-readable in the current thread&amp;#39;s culture&amp;quot;. Of course it&amp;#39;s clearer to explicitly specify the culture on both platforms.&lt;/p&gt; &lt;p&gt;The trouble is that &lt;em&gt;very&lt;/em&gt; often, it&amp;#39;s not immediately clear which of these has been implemented. This leads to guidelines such as &amp;quot;don&amp;#39;t use ToString() other than for logging&amp;quot; on the grounds that at least if it&amp;#39;s implemented inappropriately, it&amp;#39;ll only be a log file which ends up with difficult-to-understand data.&lt;/p&gt; &lt;p&gt;Should this usage be explicitly stated - perhaps even codified in the name: &amp;quot;ToDebugString&amp;quot; or something similar? I will leave this for smarter minds to think about, but I think there&amp;#39;s enough value in the method to make it worth keeping.&lt;/p&gt; &lt;h3&gt;MemberwiseClone&lt;/h3&gt; &lt;p&gt;Again, I&amp;#39;m not sure on this one. It would perhaps be better as a static (generic!) method somewhere in a class whose name indicated &amp;quot;this is for sneaky runtime stuff&amp;quot;. After all, it constructs a new object without calling a constructor, and other funkiness. I&amp;#39;m less bothered by this than the other items though.&lt;/p&gt; &lt;h3&gt;Conclusion&lt;/h3&gt; &lt;p&gt;To summarise, in an ideal world:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Equals and GetHashCode would disappear from Object. Types would have to explicitly say that they could be compared&lt;/li&gt; &lt;li&gt;Wait/Pulse/PulseAll would become instance methods in Monitor, which would be instantiated every time you want a lock.&lt;/li&gt; &lt;li&gt;ToString &lt;em&gt;might&lt;/em&gt; be renamed to give clearer usage guidance.&lt;/li&gt; &lt;li&gt;MemberwiseClone &lt;em&gt;might&lt;/em&gt; be moved to a different class.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Obviously it&amp;#39;s far too late for either Java or .NET to make these changes, but it&amp;#39;s always interesting to dream. Any more changes you&amp;#39;d like to see? Or violent disagreements with any of the above?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1655908" 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/Java/default.aspx">Java</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/CSharpDevCenter/default.aspx">CSharpDevCenter</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/CSharpDev/default.aspx">CSharpDev</category></item><item><title>C# 4.0: dynamic&lt;T&gt; ?</title><link>http://msmvps.com/blogs/jon_skeet/archive/2008/10/30/c-4-0-dynamic-lt-t-gt.aspx</link><pubDate>Thu, 30 Oct 2008 22:04:10 GMT</pubDate><guid isPermaLink="false">d67277c4-116b-43f1-b688-e9ef184ea916:1652571</guid><dc:creator>skeet</dc:creator><slash:comments>29</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/rsscomments.aspx?PostID=1652571</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://msmvps.com/blogs/jon_skeet/commentapi.aspx?PostID=1652571</wfw:comment><comments>http://msmvps.com/blogs/jon_skeet/archive/2008/10/30/c-4-0-dynamic-lt-t-gt.aspx#comments</comments><description>&lt;p&gt;I&amp;#39;ve not played with the VS2010 CTP much yet, and I&amp;#39;ve only looked briefly at the documentation and blogs about the new C# 4.0 &lt;code&gt;dynamic&lt;/code&gt; type, but a thought occurred to me: why not have the option of making it generic as a way of saying &amp;quot;I will dynamically support this set of operations&amp;quot;?&lt;/p&gt; &lt;p&gt;As an example of what I mean, suppose you have an interface &lt;code&gt;IMessageRouter&lt;/code&gt; like this:&lt;/p&gt; &lt;div class="code"&gt;&lt;span class="Modifier"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span class="ReferenceType"&gt;interface&lt;/span&gt; IMessageRouter&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span class="ValueType"&gt;void&lt;/span&gt; Send(&lt;span class="ReferenceType"&gt;string&lt;/span&gt; message, &lt;span class="ReferenceType"&gt;string&lt;/span&gt; destination);&lt;br /&gt;} &lt;/div&gt; &lt;p&gt;(This is an arbitrary example, by the way. The idea isn&amp;#39;t specifically more suitable for message routing than anything else.)&lt;/p&gt; &lt;p&gt;I may have various implementations, written in various languages (or COM) which support the &lt;code&gt;Send&lt;/code&gt; method with those parameters. Some of those implementations actually implement &lt;code&gt;IMessageRouter&lt;/code&gt; but some don&amp;#39;t. I&amp;#39;d like to be able to do the following:&lt;/p&gt; &lt;div class="code"&gt;dynamic&amp;lt;IMessageRouter&amp;gt; router = GetRouter();&lt;br /&gt;&lt;br /&gt;&lt;span class="InlineComment"&gt;// This is fine (but still invoked dynamically)&lt;/span&gt;&lt;br /&gt;router.Send(&lt;span class="String"&gt;&amp;quot;message&amp;quot;&lt;/span&gt;, &lt;span class="String"&gt;&amp;quot;skeet@pobox.com&amp;quot;&lt;/span&gt;);&lt;br /&gt;&lt;span class="InlineComment"&gt;// Compilation error: no such overload&lt;/span&gt;&lt;br /&gt;router.Send(&lt;span class="String"&gt;&amp;quot;message&amp;quot;&lt;/span&gt;, &lt;span class="String"&gt;&amp;quot;skeet@pobox.com&amp;quot;&lt;/span&gt;, 20); &lt;/div&gt; &lt;p&gt;Intellisense would work, and we&amp;#39;d still have some of the benefits of static typing but without the implementations having to know about your interface. Of course, it would be quite easy to create an implementation of the interface which did exactly this - but now imagine that instead of &lt;code&gt;IMessageRouter&lt;/code&gt; we had &lt;code&gt;MessageRouter&lt;/code&gt; - a concrete class. In this case the compiler would still restrict the caller to the public API of the class, but it wouldn&amp;#39;t have to be the real class. No checking would be performed by the compiler that your dynamic type &lt;i&gt;actually&lt;/i&gt; supported the operations - given that we&amp;#39;re talking about dynamic invocation, that would be impossible to do. It would instead be an &amp;quot;opt-in&amp;quot; restriction the client places on themselves. It could also potentially help with performance - if the binding involved realised that the &lt;i&gt;actual&lt;/i&gt; type of the dynamic object natively implemented the interface or was/derived from the class, then no real dynamic calls need be made; just route all directly. &lt;/p&gt; &lt;p&gt;This may all sound a bit fuzzy - I&amp;#39;m extremely sleepy, to be honest - but I think it&amp;#39;s a potentially interesting idea. Thoughts? &lt;/p&gt; &lt;h2&gt;Update&lt;/h2&gt;Apparently this post wasn&amp;#39;t as clear as it might be. I&amp;#39;m quite happy to keep the currently proposed dynamic type idea &lt;em&gt;as well&lt;/em&gt; - I&amp;#39;d like this as an &lt;em&gt;additional&lt;/em&gt; way of using dynamic objects.&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1652571" 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/C_2300_+4/default.aspx">C# 4</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/CSharpDevCenter/default.aspx">CSharpDevCenter</category><category domain="http://msmvps.com/blogs/jon_skeet/archive/tags/CSharpDev/default.aspx">CSharpDev</category></item></channel></rss>