<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>jaredpar's WebLog : Immutable</title><link>http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx</link><description>Tags: Immutable</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Immutable vs. Mutable Collection Performance</title><link>http://blogs.msdn.com/jaredpar/archive/2009/04/06/immutable-vs-mutable-collection-performance.aspx</link><pubDate>Mon, 06 Apr 2009 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9532916</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9532916.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9532916</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9532916</wfw:comment><description>&lt;p&gt;One argument I commonly hear against immutable collections is they are slow.&amp;#160; I’ve held the opposite belief for some time but shamefully had yet to look at actual numbers on the CLR.&amp;#160; Tonight I decided to change that by benchmarking one of &lt;a href="http://code.msdn.com/BclExtras"&gt;my immutable collections&lt;/a&gt; against a mutable collection in the BCL.&amp;#160; The goal is not to decide the overall best collection but instead to get a sense of how they perform relative to each other in certain scenarios.&lt;/p&gt;  &lt;p&gt;For the immutable version, I chose to use ImmutableCollection.&amp;#160; This class is a slight variation of Eric Lippert’s &lt;a href="http://blogs.msdn.com/ericlippert/archive/2008/02/12/immutability-in-c-part-eleven-a-working-double-ended-queue.aspx"&gt;Double Ended Queue&lt;/a&gt; implementation.&amp;#160; The core algorithm is the same but the style was changed to be more inline with other immutable collections I own. For the mutable class I chose to use the ever popular &lt;a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx"&gt;List&amp;lt;T&amp;gt;&lt;/a&gt; collection.&amp;#160; &lt;/p&gt;  &lt;p&gt;I chose to examine the following scenarios that I commonly use with collection style classes.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Adding to the end of the collection &lt;/li&gt;    &lt;li&gt;Adding to the front of the collection &lt;/li&gt;    &lt;li&gt;Removing from the end of the collection &lt;/li&gt;    &lt;li&gt;Removing from the beginning of the collection &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Each scenario was run against collections of 100, 1000 and 10000 elements.&amp;#160; For each count, the run was executed 1000 times and the total and average time was calculated.&amp;#160; The full code for the benchmark is available at the end of this post.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Looking at the data&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Now before I get into the results, please assume the usual caveats that come with any benchmark.&amp;#160; That is, approach it with a skeptical eye.&amp;#160; These scenarios are obviously not something I do &lt;strong&gt;exactly &lt;/strong&gt;in everyday programming (especially removing thousands of elements from the front of List&amp;lt;T&amp;gt;).&amp;#160; However they are representative of general operations that I do use.&amp;#160; Also I find it interesting to see how the collections perform relative to each other in extreme scenarios.&lt;/p&gt;  &lt;p&gt;Most of the results were unsurprising.&amp;#160; Remove from end is a very simple operation on a List&amp;lt;T&amp;gt;.&amp;#160; It comes down to a bounds check, decrementing an index and updating a couple of internal state variables.&amp;#160;&amp;#160; Removing the end of an immutable collection requires considerable updating of the internal structure.&amp;#160; It ends up being roughly 1 order of magnitude slower.&amp;#160;&amp;#160;&amp;#160; Adding to the end has similar implementation and numbers.&lt;/p&gt;  &lt;p&gt;Operations on the front of the list were significantly slower on List&amp;lt;T&amp;gt; than ImmutableCollection for suitably large collections.&amp;#160; This is unsurprising given that removal and insertion at the front of a List&amp;lt;T&amp;gt; requires all of the other elements in the underlying array to be shifted up or down.&amp;#160; This is a non-trivial operation and is evident in the benchmark.&amp;#160; &lt;/p&gt;  &lt;p&gt;The most interesting item however, is to look at how each collection scales.&amp;#160; In almost all scenarios, ImmutableCollection scaled very closely to the size of the input.&amp;#160; That is, an order of magnitude more input resulted in an order of magnitude of more time.&amp;#160; List&amp;lt;T&amp;gt; does not have that behavior for all scenarios.&amp;#160; Scenarios dealing with the front of the collection saw time rises faster relative to input size.&amp;#160; In fact there is a very dramatic jump in both front scenarios between 1000 and 1000 elements.&amp;#160; Each case resulted in roughly 2 orders of magnitude more time.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Winner of each category … &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Add to End: List&amp;lt;T&amp;gt; &lt;/li&gt;    &lt;li&gt;Add to Front: ImmutableCollection&amp;lt;T&amp;gt; &lt;/li&gt;    &lt;li&gt;Remove from End: List&amp;lt;T&amp;gt; &lt;/li&gt;    &lt;li&gt;Remove from Front: ImmutableCollection&amp;lt;T&amp;gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;No single benchmark is definitive and this one won’t change that.&amp;#160; This benchmark says nothing about the general use of the two classes.&amp;#160; However it can provide some insight into these specific scenarios.&amp;#160; It also serves as some level of proof that immutable collections can have acceptable performance for these scenarios.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Data&lt;/strong&gt;&lt;/p&gt;  &lt;pre&gt;Add to End 100 Elements
       List: Total: 00:00:00.0060473 Average: 00:00:00.0000060
  Immutable: Total: 00:00:00.0267079 Average: 00:00:00.0000267
Add to End 1000 Elements
       List: Total: 00:00:00.0337505 Average: 00:00:00.0000337
  Immutable: Total: 00:00:00.2240444 Average: 00:00:00.0002240
Add to End 10000 Elements
       List: Total: 00:00:00.4266014 Average: 00:00:00.0004266
  Immutable: Total: 00:00:02.6715789 Average: 00:00:00.0026715
Add to Front 100 Elements
       List: Total: 00:00:00.0162186 Average: 00:00:00.0000162
  Immutable: Total: 00:00:00.0213764 Average: 00:00:00.0000213
Add to Front 1000 Elements
       List: Total: 00:00:00.4028523 Average: 00:00:00.0004028
  Immutable: Total: 00:00:00.2055935 Average: 00:00:00.0002055
Add to Front 10000 Elements
       List: Total: 00:00:38.5943722 Average: 00:00:00.0385943
  Immutable: Total: 00:00:02.6212590 Average: 00:00:00.0026212
Remove From End 100 Elements
       List: Total: 00:00:00.0031299 Average: 00:00:00.0000031
  Immutable: Total: 00:00:00.0213737 Average: 00:00:00.0000213
Remove From End 1000 Elements
       List: Total: 00:00:00.0187998 Average: 00:00:00.0000187
  Immutable: Total: 00:00:00.1623739 Average: 00:00:00.0001623
Remove From End 10000 Elements
       List: Total: 00:00:00.1773381 Average: 00:00:00.0001773
  Immutable: Total: 00:00:01.9615781 Average: 00:00:00.0019615
Remove From Front 100 Elements
       List: Total: 00:00:00.0142981 Average: 00:00:00.0000142
  Immutable: Total: 00:00:00.0192679 Average: 00:00:00.0000192
Remove From Front 1000 Elements
       List: Total: 00:00:00.4407993 Average: 00:00:00.0004407
  Immutable: Total: 00:00:00.1879243 Average: 00:00:00.0001879
Remove From Front 10000 Elements
       List: Total: 00:00:39.7832085 Average: 00:00:00.0397832
  Immutable: Total: 00:00:02.2451406 Average: 00:00:00.0022451&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;The Code&lt;/strong&gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ImmutableCollectionAddToEnd(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; list) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;col = &lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;.Empty;
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;item &lt;span style="color: blue"&gt;in &lt;/span&gt;list) {
            col = col.AddBack(item);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ListAddToEnd(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; list) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;col = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;();
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;item &lt;span style="color: blue"&gt;in &lt;/span&gt;list) {
            col.Add(item);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;RunAddToEnd(&lt;span style="color: blue"&gt;int &lt;/span&gt;count) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;list = &lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(0, count).Select(x =&amp;gt; x.ToString()).ToList();
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Add to End {0} Elements&amp;quot;&lt;/span&gt;, count);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;List&amp;quot;&lt;/span&gt;, ListAddToEnd, () =&amp;gt; list);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;Immutable&amp;quot;&lt;/span&gt;, ImmutableCollectionAddToEnd, () =&amp;gt; list);
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ImmutableCollectionAddToFront(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; list) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;col = &lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;.Empty;
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;item &lt;span style="color: blue"&gt;in &lt;/span&gt;list) {
            col = col.AddFront(item);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ListAddToFront(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; list) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;col = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;();
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;item &lt;span style="color: blue"&gt;in &lt;/span&gt;list) {
            col.Insert(0, item);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;RunAddToFront(&lt;span style="color: blue"&gt;int &lt;/span&gt;count) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;list = &lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(0, count).Select(x =&amp;gt; x.ToString()).ToList();
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Add to Front {0} Elements&amp;quot;&lt;/span&gt;, count);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;List&amp;quot;&lt;/span&gt;, ListAddToFront, () =&amp;gt; list);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;Immutable&amp;quot;&lt;/span&gt;, ImmutableCollectionAddToFront, () =&amp;gt; list);
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ImmutableCollectionRemoveFromEnd(&lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; col) {
        &lt;span style="color: blue"&gt;while &lt;/span&gt;(!col.IsEmpty) {
            col = col.RemoveBack();
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ListRemoveFromEnd(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; list) {
        &lt;span style="color: blue"&gt;while &lt;/span&gt;(list.Count &amp;gt; 0) {
            list.RemoveAt(list.Count - 1);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;RunRemoveFromEnd(&lt;span style="color: blue"&gt;int &lt;/span&gt;count) {
        &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; listInputFunc = () =&amp;gt; &lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(0, count).Select(x =&amp;gt; x.ToString()).ToList();
        &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; colInputFunc = () =&amp;gt; &lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;.Create(listInputFunc());
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Remove From End {0} Elements&amp;quot;&lt;/span&gt;, count);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;List&amp;quot;&lt;/span&gt;, ListRemoveFromEnd, listInputFunc);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;Immutable&amp;quot;&lt;/span&gt;, ImmutableCollectionRemoveFromEnd, colInputFunc);
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ImmutableCollectionRemoveFromFront(&lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; col) {
        &lt;span style="color: blue"&gt;while &lt;/span&gt;(!col.IsEmpty) {
            col = col.RemoveFront();
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ListRemoveFromFront(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; col) {
        &lt;span style="color: blue"&gt;while &lt;/span&gt;(col.Count &amp;gt; 0) {
            col.RemoveAt(0);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;RunRemoveFromFront(&lt;span style="color: blue"&gt;int &lt;/span&gt;count) {
        &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; listInputFunc = () =&amp;gt; &lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(0, count).Select(x =&amp;gt; x.ToString()).ToList();
        &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; colInputFunc = () =&amp;gt; &lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;.Create(listInputFunc());
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Remove From Front {0} Elements&amp;quot;&lt;/span&gt;, count);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;List&amp;quot;&lt;/span&gt;, ListRemoveFromFront, listInputFunc);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;Immutable&amp;quot;&lt;/span&gt;, ImmutableCollectionRemoveFromFront, colInputFunc);
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;RunScenario&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;string &lt;/span&gt;description, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt; del, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt; getInputFunc) {
        &lt;span style="color: green"&gt;// Run once to jit
        &lt;/span&gt;del(getInputFunc());
        &lt;span style="color: blue"&gt;const int &lt;/span&gt;times = 1000;
        &lt;span style="color: blue"&gt;var &lt;/span&gt;total = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt;();
        &lt;span style="color: blue"&gt;for &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;i = 0; i &amp;lt; times; i++) {
            &lt;span style="color: green"&gt;// get the input outside the timer so input creation is not calculated 
            &lt;/span&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;input = getInputFunc();
            &lt;span style="color: blue"&gt;var &lt;/span&gt;watch = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Stopwatch&lt;/span&gt;();
            watch.Start();
            del(input);
            watch.Stop();
            total += watch.Elapsed;
        }
        &lt;span style="color: blue"&gt;var &lt;/span&gt;average = &lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt;.FromTicks(total.Ticks / times);
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0,11}: Total: {1} Average: {2}&amp;quot;&lt;/span&gt;, description, total, average);
    }
    &lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;list = &lt;span style="color: blue"&gt;new int&lt;/span&gt;[] { 100, 1000, 10000 };
        list.ForEach(RunAddToEnd);
        list.ForEach(RunAddToFront);
        list.ForEach(RunRemoveFromEnd);
        list.ForEach(RunRemoveFromFront);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9532916" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Performance/default.aspx">Performance</category></item><item><title>Why are thread safe collections so hard?</title><link>http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx</link><pubDate>Wed, 11 Feb 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9412190</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>52</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9412190.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9412190</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9412190</wfw:comment><description>&lt;p&gt;Writing a collection which is mutable, thread safe and usable is an extremely difficult process.&amp;nbsp; At least that’s what you’ve likely been told all through your schooling.&amp;nbsp; But then you get out on the web and see a multitude of thread safe lists, maps and queues.&amp;nbsp; If it’s so hard, why are there so many examples?&amp;nbsp; &lt;/p&gt;  &lt;p&gt;The problem is there are several levels of thread safe collections.&amp;nbsp; I find that when most people say thread safe collection what they really mean “a collection that will not be corrupted when modified and accessed from multiple threads”.&amp;nbsp;&amp;nbsp; Lets call this “data thread safe” for brevity.&amp;nbsp; This type of collection is rather easy to build.&amp;nbsp; Virtually any collection that is not thread safe can be made “data thread safe” by synchronizing access via a simple locking mechanism.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;For Example, lets build a data thread safe List&amp;lt;T&amp;gt;.&amp;nbsp; &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeList&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: rgb(43, 145, 175);"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;    &lt;span style="color: blue;"&gt;private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt; m_list = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt;();&lt;br&gt;    &lt;span style="color: blue;"&gt;private object &lt;/span&gt;m_lock = &lt;span style="color: blue;"&gt;new object&lt;/span&gt;();&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Add(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_list.Add(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Remove(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_list.Remove(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;Contains(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list.Contains(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Count { &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list.Count; } } }&lt;br&gt;    &lt;span style="color: blue;"&gt;public &lt;/span&gt;T &lt;span style="color: blue;"&gt;this&lt;/span&gt;[&lt;span style="color: blue;"&gt;int &lt;/span&gt;index] {&lt;br&gt;        &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list[index]; } }&lt;br&gt;        &lt;span style="color: blue;"&gt;set &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { m_list[index] = &lt;span style="color: blue;"&gt;value&lt;/span&gt;; } }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: green;"&gt;// IEnumerable&amp;lt;T&amp;gt; left out&lt;br&gt;&lt;/span&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;And there you have it.&amp;nbsp; The lock statement prevents concurrent access from multiple threads.&amp;nbsp; So the actual m_list instance is only ever accessed by a single thread at a time which is all it’s designed to do.&amp;nbsp; This means instances of ThreadSafeList&amp;lt;T&amp;gt; can be used from any thread without fear of corrupting the underlying data.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;But if building a data thread safe list is so easy, why doesn’t Microsoft add these standard collections in the framework?&lt;/p&gt;

&lt;p&gt;Answer: ThreadSafeList&amp;lt;T&amp;gt; is a virtually unusable class because the design leads you down the path to bad code.&lt;/p&gt;

&lt;p&gt;The flaws in this design are not apparent until you examine how lists are commonly used.&amp;nbsp; For example,&amp;nbsp; take the following code which attempts to grab the first element out of the list if there is one.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;static int &lt;/span&gt;GetFirstOrDefault(&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeList&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt; list) {&lt;br&gt;    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(list.Count &amp;gt; 0) {&lt;br&gt;        &lt;span style="color: blue;"&gt;return &lt;/span&gt;list[0];&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;return &lt;/span&gt;0;&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This code is a classic race condition.&amp;nbsp; Consider the case where there is only one element in the list.&amp;nbsp; If another thread removes that element in between the if statement and the return statement, the return statement will throw an exception because it’s trying to access an invalid index in the list.&amp;nbsp; Even though ThreadSafeList&amp;lt;T&amp;gt; is data thread safe, there is nothing guaranteeing the validity of a return value of one call across the next call to the same object.&amp;nbsp;&amp;nbsp; &lt;/p&gt;

&lt;p&gt;I refer to procedures like Count as decision procedures.&amp;nbsp; They server only to allow you to make a decision about the underlying object.&amp;nbsp; Decision procedures on a concurrent object are virtually useless.&amp;nbsp; As soon as the decision is returned, you must assume the object has changed and hence you cannot use the result to take any action.&lt;/p&gt;

&lt;p&gt;Decision procedures are one of the reasons why &lt;a href="http://code.msdn.microsoft.com/BclExtras" mce_href="http://code.msdn.microsoft.com/BclExtras"&gt;Immutable Collections&lt;/a&gt; are so attractive.&amp;nbsp; They are both data thread safe and allow you to reason about there APIs.&amp;nbsp; Immutable Collections don’t change &lt;b&gt;ever.&amp;nbsp; &lt;/b&gt;Hence it’s perfectly ok to have decision procedures on them because the result won’t get invalidated.&lt;/p&gt;

&lt;p&gt;The fundamental issue with ThreadSafeList&amp;lt;T&amp;gt; is it is designed to act like a List&amp;lt;T&amp;gt;.&amp;nbsp; Yet List&amp;lt;T&amp;gt; is not designed for concurrent access.&amp;nbsp;&amp;nbsp; When building a mutable concurrent collection, in addition to considering the validity of the data, you must consider how design the API to deal with the constantly changing nature of the collection.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;When designing a concurrent collection you should follow different guidelines than for a normal collection class.&amp;nbsp; For example.&amp;nbsp; &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Don’t add an decision procedures.&amp;nbsp; They lead users down the path to bad code. &lt;/li&gt;

  &lt;li&gt;Methods which query the object can always fail and the API should reflect this. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Based on that, lets look at a refined design for ThreadSafeList&amp;lt;T&amp;gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeList&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;    &lt;span style="color: blue;"&gt;private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt; m_list = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt;();&lt;br&gt;    &lt;span style="color: blue;"&gt;private object &lt;/span&gt;m_lock = &lt;span style="color: blue;"&gt;new object&lt;/span&gt;();&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Add(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_list.Add(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;TryRemove(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list.Remove(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;TryGet(&lt;span style="color: blue;"&gt;int &lt;/span&gt;index, &lt;span style="color: blue;"&gt;out &lt;/span&gt;T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;( m_lock ) {&lt;br&gt;            &lt;span style="color: blue;"&gt;if&lt;/span&gt;( index &amp;lt; m_list.Count ) {&lt;br&gt;                value = m_list[index];&lt;br&gt;                &lt;span style="color: blue;"&gt;return true&lt;/span&gt;;&lt;br&gt;            }&lt;br&gt;            value = &lt;span style="color: blue;"&gt;default&lt;/span&gt;(T);&lt;br&gt;            &lt;span style="color: blue;"&gt;return false&lt;/span&gt;;&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Summary of the changes&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Both the Contains and Count procedures were removed because they were decision procedures &lt;/li&gt;

  &lt;li&gt;Remove was converted to TryRemove to indicate it’s potential to fail &lt;/li&gt;

  &lt;li&gt;The TryGet property was added and is reflective of the fragile nature of the method.&amp;nbsp; Sure it’s possible for users to simply ignore the return value and plow on with the invalid value.&amp;nbsp; However the API is not lulling the user into a false sense of security &lt;/li&gt;

  &lt;li&gt;The collection no longer implements IEnumerable&amp;lt;T&amp;gt;.&amp;nbsp; IEnumerable&amp;lt;T&amp;gt; is only valid when a collection is not changing under the hood.&amp;nbsp; There is no way to easily make this guarantee with a collection built this way and hence it was removed.&amp;nbsp; &lt;/li&gt;

  &lt;li&gt;The indexers were removed as well.&amp;nbsp; I’m a bit wishy washy in this particular point as there is nothing in the API which gives a user a false sense of security.&amp;nbsp; But at the same time mutable concurrent collections are dangerous and should be treated with a heightened sense of respect so the indexers were removed. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This version of ThreadSafeList is more resilient, but not immune to, accidental user failure.&amp;nbsp; The design tends to lead users on the path to better code.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;But is it really usable?&amp;nbsp; Would you use it in your application?&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9412190" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>Immutable Collections and Compatibility with Existing Frameworks</title><link>http://blogs.msdn.com/jaredpar/archive/2008/12/10/immutable-collections-and-backwards-compatibility.aspx</link><pubDate>Wed, 10 Dec 2008 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9187707</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9187707.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9187707</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9187707</wfw:comment><description>&lt;P&gt;When developing my &lt;A href="http://code.msdn.microsoft.com/RantPack" mce_href="http://code.msdn.microsoft.com/RantPack"&gt;immutable collections library&lt;/A&gt;, I spent a lot of time on usability.&amp;nbsp; After all, if a library is not useful then what’s the point?&lt;/P&gt;
&lt;P&gt;A big portion of usability is being able to work with existing frameworks and technologies.&amp;nbsp; For .Net and collections that means items like Data binding, LINQ etc …&amp;nbsp; Without integrating into popular technologies the usefulness of a particular library is severely impacted and hence usability decreases.&lt;/P&gt;
&lt;P&gt;Most of the existing collection based infrastructures use the .Net collection interfaces as their form of abstraction.&amp;nbsp; The most straight forward way to ensure compatibility is to implement these interfaces on the collections in question.&amp;nbsp; In particular &lt;A href="http://msdn.microsoft.com/en-us/library/92t2ye13.aspx" mce_href="http://msdn.microsoft.com/en-us/library/92t2ye13.aspx"&gt;ICollection&amp;lt;T&amp;gt;&lt;/A&gt;, &lt;A href="http://msdn.microsoft.com/en-us/library/5y536ey6.aspx" mce_href="http://msdn.microsoft.com/en-us/library/5y536ey6.aspx"&gt;IList&amp;lt;T&amp;gt;&lt;/A&gt; and &lt;A href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" mce_href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx"&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/A&gt; are the main abstractions.&amp;nbsp; Lets investigate which ones an Immutable collection should be implementing in order to effectively integrate into existing collection based infrastructures.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;This is the easiest decision.&amp;nbsp; IEnumerable&amp;lt;T&amp;gt; represents a read only, one element at time view on a sequence of objects.&amp;nbsp; Immutable collections can easily and reliably implement a IEnumerable&amp;lt;T&amp;gt;.&amp;nbsp; This is a no brainer.&amp;nbsp; Implement.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;ICollection&amp;lt;T&amp;gt;&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;This interfaces represents a general collection class.&amp;nbsp; Unfortunately this interface is meant to represent a mutable collection class and implements such methods as Add, Clear and Remove.&amp;nbsp; These methods cannot be implemented on an Immutable collection given the current design.&amp;nbsp; All three of these methods are void returning methods because the collection is meant to be changed in place.&amp;nbsp; Immutable collections can support these operations but it involves returning a new instance of the collection.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;public sealed class &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;ImmutableCollection&lt;/SPAN&gt;&amp;lt;T&amp;gt; : &lt;SPAN style="COLOR: #2b91af"&gt;ICollection&lt;/SPAN&gt;&amp;lt;T&amp;gt; {
    &lt;SPAN style="COLOR: blue"&gt;public &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;ImmutableCollection&lt;/SPAN&gt;&amp;lt;T&amp;gt; Add(T item) {
        &lt;SPAN style="COLOR: green"&gt;// Actually add 
        // ...
    &lt;/SPAN&gt;}

    &lt;SPAN style="COLOR: blue"&gt;#region &lt;/SPAN&gt;ICollection&amp;lt;T&amp;gt; Members

    &lt;SPAN style="COLOR: blue"&gt;void &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;ICollection&lt;/SPAN&gt;&amp;lt;T&amp;gt;.Add(T item) {
        &lt;SPAN style="COLOR: blue"&gt;var &lt;/SPAN&gt;created = &lt;SPAN style="COLOR: blue"&gt;this&lt;/SPAN&gt;.Add(item);
        &lt;SPAN style="COLOR: green"&gt;// What to do with created???
    &lt;/SPAN&gt;}

    ...
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;But wait!&amp;nbsp; The interface does support a property named &lt;A href="http://msdn.microsoft.com/en-us/library/0cfatk9t.aspx" mce_href="http://msdn.microsoft.com/en-us/library/0cfatk9t.aspx"&gt;IsReadOnly&lt;/A&gt;.&amp;nbsp; The intention of this property is to allow an interface to programmatically declare they do not support modifications.&amp;nbsp; A read only collection can just implement this interface, throw a&amp;nbsp;&lt;A class="" title=NotSupportedException href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx"&gt;NotSupportedException&lt;/A&gt; for all of the mutable methods and return true for IsReadOnly and presto we have a suitable interface for an immutable collection.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Or do we?&amp;nbsp; &lt;/P&gt;
&lt;P&gt;The design for ICollection&amp;lt;T&amp;gt; with respect to read only or immutable collections is not optimal.&amp;nbsp; It attempts to combine to separate behaviors into a single interface: mutable and readonly view of a collection.&amp;nbsp; Dual purpose interfaces run into problems because it’s impossible to separate out the behaviors at compile time.&amp;nbsp; This is especially problematic when the behaviors are conflicting.&amp;nbsp; There is no way a read only collection can prevent itself from being passed to a function that expects a mutable collection at compile time.&amp;nbsp; Nor can a consumer who intends to mutate a collection prevent a read-only collection from being passed. &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;static void &lt;/SPAN&gt;DisplayForEdit&amp;lt;T&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;ICollection&lt;/SPAN&gt;&amp;lt;T&amp;gt; col) {
    &lt;SPAN style="COLOR: green"&gt;// ...
    &lt;/SPAN&gt;m_clearButton.Click += (x, y) =&amp;gt; col.Clear(); 
}

&lt;SPAN style="COLOR: blue"&gt;static void &lt;/SPAN&gt;Example1() {
    &lt;SPAN style="COLOR: #2b91af"&gt;ImmutableCollection&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: blue"&gt;int&lt;/SPAN&gt;&amp;gt; col = &lt;SPAN style="COLOR: #2b91af"&gt;ImmutableCollection&lt;/SPAN&gt;.Create(&lt;SPAN style="COLOR: blue"&gt;new int&lt;/SPAN&gt;[] { 1, 2, 3, 4 });
    DisplayForEdit(col);    &lt;SPAN style="COLOR: green"&gt;// Will fail as soon as Clear is clicked
&lt;/SPAN&gt;}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;But isn’t it the responsibility of the user of ICollection&amp;lt;T&amp;gt; to verify that IsReadOnly is false before mutating a instance?&amp;nbsp; Given the current design of ICollection&amp;lt;T&amp;gt; it is indeed both the responsibility of the consumer to verify this and the implementer to ensure they are not called incorrectly.&amp;nbsp; The problem with putting responsibility on the consumer though is they have to 1) know about read only uses of ICollection&amp;lt;T&amp;gt; and 2) actually care about it.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;A quick search of the BCL with reflector can give us evidence of how much consumers actually check for the read only scenario.&amp;nbsp; For the search I used mscorlib, System, System.Xml, System.Data, System.Drawing and System.Core and System.Windows.Forms.&amp;nbsp; And the number of classes which actually take into account ICollection&amp;lt;T&amp;gt;.IsReadOnly is … 1.&amp;nbsp; System.Collections.ObjectModel.Collection&amp;lt;T&amp;gt;.&amp;nbsp; That’s it.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;So even if an immutable collection implements this interface in a read-only fashion there’s little chance anyone will be checking for it.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;IList&amp;lt;T&amp;gt;&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;IList&amp;lt;T&amp;gt; inherits from ICollection&amp;lt;T&amp;gt; and hence suffers from all of the same problems&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Decision Time&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;In order to facilitate usability with existing frameworks immutable collections are forced to implement interfaces for which they have no possible way of implementing properly.&amp;nbsp; If collections implement these interfaces they will be trading usability for compile time validation.&amp;nbsp; Even worse is the conversion is implicit which prevents even basic searches for places this conversion occurs.&amp;nbsp; This is a heavy price to pay for compatibility. &lt;/P&gt;
&lt;P&gt;After debating this for awhile I decided that loss of compile time validation was a too heavy of a price to pay for the default scenario.&amp;nbsp; But trading away usability was also unacceptable.&amp;nbsp; As a compromise I opted for adding a compatibility layer to the collections.&amp;nbsp; Instead of implementing the ICollection&amp;lt;T&amp;gt; and IList&amp;lt;T&amp;gt; collections directly I created a set of proxy objects that implement the interfaces on behalf of the immutable collections.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;In order to centralize this effort I created a factory class, CollectionUtility, which contains appropriate overloads for all of my immutable collection classes [1].&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;public static class &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CollectionUtility &lt;/SPAN&gt;{
    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;IEnumerable&lt;/SPAN&gt;&amp;lt;T&amp;gt; CreateEmptyEnumerable&amp;lt;T&amp;gt;();
    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;IEnumerable&lt;/SPAN&gt;&amp;lt;T&amp;gt; CreateEnumerable&amp;lt;T&amp;gt;(T value);
&lt;SPAN style="COLOR: green"&gt;    &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;ICollection&lt;/SPAN&gt;&amp;lt;T&amp;gt; CreateICollection&amp;lt;T&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;IReadOnlyCollection&lt;/SPAN&gt;&amp;lt;T&amp;gt; col);
    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;IDictionary&lt;/SPAN&gt;&amp;lt;TKey, TValue&amp;gt; CreateIDictionary&amp;lt;TKey, TValue&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;IReadOnlyMap&lt;/SPAN&gt;&amp;lt;TKey, TValue&amp;gt; map);
&lt;SPAN style="COLOR: green"&gt;    &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;IList&lt;/SPAN&gt;&amp;lt;T&amp;gt; CreateIList&amp;lt;T&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;IReadOnlyList&lt;/SPAN&gt;&amp;lt;T&amp;gt; list);
    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;ICollection &lt;/SPAN&gt;CreateObjectICollection&amp;lt;T&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;IReadOnlyCollection&lt;/SPAN&gt;&amp;lt;T&amp;gt; col);
    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;IDictionary &lt;/SPAN&gt;CreateObjectIDictionary&amp;lt;TKey, TValue&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;IReadOnlyMap&lt;/SPAN&gt;&amp;lt;TKey, TValue&amp;gt; map);
    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;IList &lt;/SPAN&gt;CreateObjectIList&amp;lt;T&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;IReadOnlyList&lt;/SPAN&gt;&amp;lt;T&amp;gt; list);
    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;IEnumerable&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: blue"&gt;int&lt;/SPAN&gt;&amp;gt; GetRangeCount(&lt;SPAN style="COLOR: blue"&gt;int &lt;/SPAN&gt;start, &lt;SPAN style="COLOR: blue"&gt;int &lt;/SPAN&gt;count);
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;The proxy objects live as private inner classes inside CollectionUtility.&amp;nbsp; They implement the collection interfaces in the most read-only way possible.&amp;nbsp; When confronted with mutating calls, the proxies throw &lt;A class="" title=NotSupportedException href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx"&gt;NotSupportedException&lt;/A&gt;.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;So at the end of the day I have compile time validation for immutable collections.&amp;nbsp; If a developer wants to use them in a less than safe scenario it requires an explicit conversion.&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;static void &lt;/SPAN&gt;Example2() { 
  &lt;SPAN style="COLOR: blue"&gt;var &lt;/SPAN&gt;col = &lt;SPAN style="COLOR: #2b91af"&gt;ImmutableCollection&lt;/SPAN&gt;.Create(&lt;SPAN style="COLOR: blue"&gt;new int&lt;/SPAN&gt;[] { 1, 2, 3, 4 }); 
  &lt;SPAN style="COLOR: green"&gt;// Still fails, but explicit conversion required 
  &lt;/SPAN&gt;DisplayForEdit(&lt;SPAN style="COLOR: #2b91af"&gt;CollectionUtility&lt;/SPAN&gt;.CreateICollection(col)); 
  }&lt;/PRE&gt;
&lt;P&gt;I feel like this as an appropriate tradeoff.&amp;nbsp;&amp;nbsp; In the worst case scenario, a developer can search for all accesses of the CollectionUtility class and find places where a proxy is being created.&lt;/P&gt;
&lt;P&gt;Next time, lets take a look at a different way of approaching an interface hierarchy for a set of collections.&amp;nbsp; One that will allow us to avoid this problem altogether going forward.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;[1] It actually contains overloads for a set of truly read only collection interfaces that I wrote for my library but we’ll get to that another time.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Edit: Updated the exception to be NotSupportedException&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9187707" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Generics/default.aspx">Generics</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/RantPack/default.aspx">RantPack</category></item><item><title>A Lesson in Serialization</title><link>http://blogs.msdn.com/jaredpar/archive/2008/09/02/a-lesson-in-serialization.aspx</link><pubDate>Tue, 02 Sep 2008 15:00:46 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8904579</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8904579.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8904579</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8904579</wfw:comment><description>&lt;p&gt;A few days ago, I recklessly added a [Serialization] attribute to a few of my immutable collection types.&amp;#160; I needed to pass data between AppDomain's and adding [Serialization] was the quick and dirty fix.&amp;#160; Compiled, ran and I didn't think much about it.&amp;#160; &lt;/p&gt;  &lt;p&gt;Luckily I was updating some unit tests last night and I remembered this and added a couple of serialization sanity tests.&amp;#160; Most of the tests passed first time but for my ImmutableStack class[1] was throwing an exception.&amp;#160; Well, it was actually my ImmutableQueue but it was failing in one of the inner ImmutableStack instances.&amp;#160; The test code was fairly straight forward&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;stack = &lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;.Create(&lt;span style="color: blue"&gt;new int&lt;/span&gt;[] { 1, 2, 3 });
&lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;stream = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MemoryStream&lt;/span&gt;()) {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;f = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BinaryFormatter&lt;/span&gt;();
    f.Serialize(stream,stack);
    stream.Position = 0;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;obj = f.Deserialize(stream);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;stack2 = (&lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;)obj;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;stack3 = stack2.Reverse();
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I did a bit of digging and discovered the exception was coming from the stack2.Reverse() call.&amp;#160; Jumped through the code and didn't see much wrong.&amp;#160; I had several existing tests around ImmutableStack.Reverse() and I couldn't see why Serialization would make any difference.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;T&amp;gt; Reverse() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;r = &lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;T&amp;gt;.Empty;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;current = &lt;span style="color: blue"&gt;this&lt;/span&gt;;
    &lt;span style="color: blue"&gt;while &lt;/span&gt;(current != &lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;T&amp;gt;.Empty) {
        r = r.Push(current.Peek());
        current = current.Pop();
    }

    &lt;span style="color: blue"&gt;return &lt;/span&gt;r;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Can you see what's wrong with the code?&lt;/p&gt;

&lt;p&gt;It took me a few minutes of debugging and frustration.&amp;#160; The bug is in the while loop conditional.&amp;#160; Until you introduce serialization this code is just fine.&amp;#160; ImmutableStack&amp;lt;T&amp;gt;.Empty is a static readonly declaration.&amp;#160; The code implementation only allows for one to be created so it a singleton and equality can be done with a quick reference check. &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;private static readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EmptyImmutableStack &lt;/span&gt;s_empty = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EmptyImmutableStack&lt;/span&gt;();

&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;T&amp;gt; Empty {
    &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;s_empty; }
}&lt;/pre&gt;

&lt;p&gt;Unfortunately serialization breaks the assumption that EmptyImmutableStack is a singleton.&amp;#160; The EmptyImmutableStack class is a singleton by convention only.&amp;#160; It's a private nested class that's only instantiated once per AppDomain.&amp;#160; There is nothing stopping the CLR or Serialization for that matter from creating a second instance.&amp;#160; In the case of deserialization that's exactly what happens.&amp;#160; The serializer isn't built to recognize this pattern and instead simply creates a new instance of EmptyImmutableStack upon deserialization.&amp;#160; &lt;/p&gt;

&lt;p&gt;This essentially prevents you from safely using a functional style Empty pattern inside a serializable collection.&amp;#160; &lt;/p&gt;

&lt;p&gt;The fix is simple enough, alter the conditional to be (!current.IsEmpty).&amp;#160; &lt;/p&gt;

&lt;p&gt;[1] The version of ImmutableStack I'm using is heavily based off of &lt;a href="http://blogs.msdn.com/ericlippert/archive/2007/12/04/immutability-in-c-part-two-a-simple-immutable-stack.aspx"&gt;Eric Lippert's implementation&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8904579" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Testing/default.aspx">Testing</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category></item><item><title>ImmutableStack in F# Part 2</title><link>http://blogs.msdn.com/jaredpar/archive/2008/08/19/immutablestack-in-f-part-2.aspx</link><pubDate>Tue, 19 Aug 2008 15:00:20 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8871247</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8871247.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8871247</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8871247</wfw:comment><description>&lt;p&gt;I'm a bit busier than I thought I would be after returning from vacation.&amp;#160; But I had a little bit of time to play around with the implementation again today.&amp;#160; Thanks to all the suggestions in the comments from the &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/08/15/immutablestack-in-f.aspx"&gt;previous post&lt;/a&gt;.&amp;#160; &lt;/p&gt;  &lt;p&gt;This version has a couple of improvements including &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Removing the ambiguous constructor&lt;/li&gt;    &lt;li&gt;More efficient All() implementation&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Remaining issues:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Need to make it generic :)&lt;/li&gt;    &lt;li&gt;Still exposing a type union.&amp;#160; Great for F# but it produces somewhat awkward looking metadata for non-F# languages to consume&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;#light &lt;/p&gt;  &lt;p&gt;namespace Col   &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; type ImmutableStack =    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; | EmptyStack    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; | Value of int * ImmutableStack    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; static member Empty = EmptyStack    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; static member Create( l:#seq&amp;lt;int&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; let s = ref ImmutableStack.Empty    &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; l |&amp;gt; Seq.iter (fun n -&amp;gt; s := (!s).Push(n) )    &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; !s    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; member x.Count =     &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; let rec count t (cur:ImmutableStack) =    &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; match cur.IsEmpty with     &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; | true -&amp;gt; t    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; | false -&amp;gt; count (t+1) (cur.Pop())    &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; count 0 x    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; member x.IsEmpty =     &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; match x with    &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; | EmptyStack -&amp;gt; true    &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;gt; false    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; member x.Push(y) = Value(y,x)    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; member x.Peek() =    &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; match x with    &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; | EmptyStack -&amp;gt; failwith &amp;quot;ImmutableStack is empty&amp;quot;    &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; | Value (v,_) -&amp;gt; v    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; member x.Pop() =    &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; match x with     &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; | EmptyStack -&amp;gt; failwith &amp;quot;ImmutableStack is empty&amp;quot;    &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; | Value (_,n) -&amp;gt; n    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; member x.Reverse() =    &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; let rec doBuild (cur:ImmutableStack) (building:ImmutableStack) =    &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; match cur.IsEmpty with    &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; | true -&amp;gt; building    &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; | false -&amp;gt; doBuild (cur.Pop()) (building.Push(cur.Peek()))    &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; doBuild x ImmutableStack.Empty    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; member x.All() =    &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; match x with     &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; | EmptyStack-&amp;gt; Seq.empty&amp;lt;int&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; | Value (v,n) -&amp;gt; seq {    &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; yield v    &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; yield! n.All() }&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8871247" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/F_2300_/default.aspx">F#</category></item><item><title>Immutability and ReadOnlyCollection&lt;T&gt;</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/22/api-design-readonlycollection-t.aspx</link><pubDate>Tue, 22 Apr 2008 15:42:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8415163</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8415163.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8415163</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8415163</wfw:comment><description>&lt;P&gt;I am a huge fan of read only/immutable collections and data.&amp;nbsp; Hopefully the increased exposure through the blogosphere alerted users to the advantages of this type of programming for the appropriate scenarios.&amp;nbsp; I wanted to discuss &lt;A href="http://msdn2.microsoft.com/en-us/library/ms132474.aspx" mce_href="http://msdn2.microsoft.com/en-us/library/ms132474.aspx"&gt;ReadOnlyCollection&amp;lt;T&amp;gt;&lt;/A&gt;&amp;nbsp;in case devs looking around in the BCL discover&amp;nbsp;it and assume it's immutable.&amp;nbsp; There are two details of this class which cause gotchas and design issues for consumers who assume it is immutable.&lt;/P&gt;
&lt;H3&gt;It implements IList&amp;lt;T&amp;gt;&lt;/H3&gt;
&lt;P&gt;&lt;A href="http://msdn2.microsoft.com/en-us/library/5y536ey6.aspx" mce_href="http://msdn2.microsoft.com/en-us/library/5y536ey6.aspx"&gt;IList&amp;lt;T&amp;gt;&lt;/A&gt; is a interface describing mutable collection types which support indexing.&amp;nbsp; ReadOnlyCollection is designed to be read only and cannot fulfill this contract.&amp;nbsp; Therfore every mutable function will throw an exception.&amp;nbsp; IMHO this is not the best design because it is&amp;nbsp;implementing a contract it won't every fullfill.&amp;nbsp; This has the effect of turning what should be a compile time error into a runtime exception (passing a non-mutable collection to an API expecting a mutable collection).&lt;/P&gt;
&lt;P&gt;Unfortunately there is not a good interface to implement.&amp;nbsp; The indexable interfaces are all representative of mutable collection types.&amp;nbsp; It would be nice to add an immutable/read only interface which can be safely implemented.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;interface&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;IReadOnlyList&lt;/SPAN&gt;&amp;lt;T&amp;gt; : &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;IEnumerable&lt;/SPAN&gt;&amp;lt;T&amp;gt;
    {
        T &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;this&lt;/SPAN&gt;[&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; index] { &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;get&lt;/SPAN&gt;; }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; Count { &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;get&lt;/SPAN&gt;; }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; IndexOf(T value);
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; Contains(T item);
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; CopyTo(T[] array, &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; arrayIndex);
    }&lt;/PRE&gt;
&lt;P&gt;Ideally this would be called IImmutableList&amp;lt;T&amp;gt; but I'm having trouble getting over the double I, double M pattern to start the name.&amp;nbsp; Perhaps IPersistentList.&lt;/P&gt;
&lt;H3&gt;It's not deeply ReadOnly&lt;/H3&gt;
&lt;P&gt;ReadOnlyCollection&amp;lt;T&amp;gt; is a read only facade on top of mutable collection.&amp;nbsp; Read only data should be just that, read only.&amp;nbsp; This means calling methods directly on the class produce the same result every single time.&amp;nbsp; However because it uses a mutable backing store this is not true and can cause gotchas along the road. &lt;/P&gt;
&lt;P&gt;Take the following sample which uses a ReadOnlyCollection to wrap a List.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; list = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;List&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;();
            list.AddRange(&lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Enumerable&lt;/SPAN&gt;.Range(1, 10));

            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; roList = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ReadOnlyCollection&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;(list);
            &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Console&lt;/SPAN&gt;.WriteLine(roList.Count);    &lt;SPAN style="COLOR: rgb(0,128,0)"&gt;// Outputs: 10
&lt;/SPAN&gt;            list.Add(42);
            &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Console&lt;/SPAN&gt;.WriteLine(roList.Count);    &lt;SPAN style="COLOR: rgb(0,128,0)"&gt;// Outputs: 11&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;There are ways to avoid this problem with ReadOnlyCollectionn.&amp;nbsp; The simplest is to make sure you pass a copy of your list into the constructor.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; roList2 = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ReadOnlyCollection&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;List&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;(list));&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8415163" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>PipeSingleReaderNoLock</title><link>http://blogs.msdn.com/jaredpar/archive/2008/03/03/pipesinglereadernolock.aspx</link><pubDate>Mon, 03 Mar 2008 08:46:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7996040</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7996040.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7996040</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7996040</wfw:comment><description>&lt;P&gt;Previously we discussed a multi-thread safe &lt;A href="http://blogs.msdn.com/jaredpar/archive/2008/03/02/pipesinglereader.aspx" mce_href="http://blogs.msdn.com/jaredpar/archive/2008/03/02/pipesinglereader.aspx"&gt;queue like data structure&lt;/A&gt; using locks as an internal synchronization mechanism.&amp;nbsp; This time we'll look at a version requiring no locks.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;In the previous version, locks were used to synchronize access to an underlying queue which stored the data.&amp;nbsp; Removing the locks necessitates us moving away from Queue&amp;lt;T&amp;gt; to store the data and forces us onto another structure which is safe in the presence of multiple threads.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Immutable collections are safe in the presence of multiple threads and don't require any synchronization mechanisms.&amp;nbsp; However they're immutable and we're trying to build a mutable data structure?&amp;nbsp; No matter.&amp;nbsp; Even though each instance is immutable they can be used to create new instances which represent a somewhat mutated state.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;For this exercise we will be using a slight variant of Eric Lippert's &lt;A href="http://blogs.msdn.com/ericlippert/archive/2007/12/04/immutability-in-c-part-two-a-simple-immutable-stack.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2007/12/04/immutability-in-c-part-two-a-simple-immutable-stack.aspx"&gt;Immutable Stack&lt;/A&gt; implementation [1].&amp;nbsp; The pipe will have two stacks; 1) for capturing input and 2) for storing output.&amp;nbsp; Named m_writeStack and m_readStack respectively.&lt;/P&gt;
&lt;P&gt;This makes the implementation of reading input straight forward.&amp;nbsp; While m_readStack is not empty the reader thread can systematically pop off the values.&amp;nbsp; This doesn't require any contention with writer threads and since their is only one reader thread and the stack is immutable the code is straight forward.&amp;nbsp; Once the m_readStack is empty the reader thread will swap out the current state of m_writeStack with an empty stack.&amp;nbsp; The original value will be reversed so we can maintain the FIFO ordering and set as the new m_readStack.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; CheckForInput() {
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt;( m_readerStack.IsEmpty ) {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; prev = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Interlocked&lt;/SPAN&gt;.Exchange(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;ref&lt;/SPAN&gt; m_writerStack, &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt;.Empty);
        m_readerStack = prev.Reverse();
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; !m_readerStack.IsEmpty;
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;Writing data is more complicated because it must deal with contention for updating the same data structure.&amp;nbsp; It can be altered by other writers or the reader thread when it runs out of data.&amp;nbsp; Basically it must push a value onto the stack and update the m_writerStack to point to the new value.&amp;nbsp; In between the operations the value of m_writerStack could change and thus invalidate the push.&amp;nbsp; To guard against this the writer must guarantee the current value of the m_writerStack is the same as it was before the push operation.&amp;nbsp; Interlocked.CompareExchange will do the trick.&amp;nbsp; If it's been changed then repeat the operation.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AddInput(T value) {
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; done;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;do&lt;/SPAN&gt; {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (m_inputClosed) {
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;InvalidOperationException&lt;/SPAN&gt;(&lt;SPAN style="COLOR: rgb(163,21,21)"&gt;"Input end of pipe is closed"&lt;/SPAN&gt;);
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; originalStack = m_writerStack;
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; newStack = originalStack.Push(value);
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; currentStack = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Interlocked&lt;/SPAN&gt;.CompareExchange(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;ref&lt;/SPAN&gt; m_writerStack, newStack, originalStack);
        done = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;object&lt;/SPAN&gt;.ReferenceEquals(currentStack, originalStack);
    } &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;while&lt;/SPAN&gt; (!done);
    m_event.Set();
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;At a glance it may seem like this suffers from the &lt;A href="http://en.wikipedia.org/wiki/ABA_problem" mce_href="http://en.wikipedia.org/wiki/ABA_problem"&gt;ABA problem&lt;/A&gt;.&amp;nbsp; This is not the case and it's easy to prove.&amp;nbsp; In between the read and push operation only two other operations can modify the m_writeStack variable.&amp;nbsp; The first is another write which will produce a new value of ImmutableStack&amp;lt;T&amp;gt;.&amp;nbsp; In this case the CLR guarantees that the references will not be equal and the CAS operation won't succeed.&amp;nbsp; The second is the reader thread swaps out the value and replaces it with Empty.&amp;nbsp; It's possible to hit an ABA situation here (detailed below) but fundamentally if it was empty before and empty now the operation is still safe.&amp;nbsp; No data is lost&amp;nbsp;because we are still replacing an empty stack with a single value'd stack.&amp;nbsp;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Here's a more elaborate version starting with an empty pipe of type int&lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;Thread 1: Begins to write 5 and is stopped just before the CAS operation&lt;/LI&gt;
&lt;OL&gt;
&lt;LI&gt;originalStack points to ImmutableStack&amp;lt;int&amp;gt;.Empty&lt;/LI&gt;&lt;/OL&gt;
&lt;LI&gt;Thread 2: Starts and completes a write of the value 6&lt;/LI&gt;
&lt;LI&gt;Thread 3: Reads a value from the pipe, having no data replaces m_writeStack with ImmutableStack&amp;lt;int&amp;gt;.Empty&lt;/LI&gt;
&lt;LI&gt;Thread 1: Resumes and the CAS succeeds even though the m_writeStack technically changed in the middle of the operation&lt;/LI&gt;&lt;/OL&gt;
&lt;P&gt;Even though this exhibits many characterstics of the ABA pattern it is not a problem because the behavior is still correct.&amp;nbsp; No data was lost because it was transferred to the reader thread.&amp;nbsp;&amp;nbsp;The end result is m_writeStack pointing to a single vaue'd stack containing the data 5 which is valid.&amp;nbsp;&amp;nbsp;The pipe does not guarantee the ordering of data between writer threads (merely the ordering between a single writer thread).&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Below is the implementation in it's entirety.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;class&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;PipeSingleReaderNoLock&lt;/SPAN&gt;&amp;lt;T&amp;gt; : &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;IDisposable&lt;/SPAN&gt; {
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;readonly&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ThreadAffinity&lt;/SPAN&gt; m_affinity = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ThreadAffinity&lt;/SPAN&gt;();
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt; m_readerStack = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt;.Empty;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt; m_writerStack = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt;.Empty;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;readonly&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;AutoResetEvent&lt;/SPAN&gt; m_event = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;AutoResetEvent&lt;/SPAN&gt;(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;false&lt;/SPAN&gt;);
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;volatile&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; m_inputClosed;

    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; PipeSingleReaderNoLock() {
    }

&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;    #region&lt;/SPAN&gt; Dispose
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; Dispose() {
        Dispose(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;true&lt;/SPAN&gt;);
        &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;GC&lt;/SPAN&gt;.SuppressFinalize(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;this&lt;/SPAN&gt;);
    }
    ~PipeSingleReaderNoLock() {
        Dispose(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;false&lt;/SPAN&gt;);
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; Dispose(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; disposing) {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (disposing) {
            m_event.Close();
        }
    }
&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;    #endregion
&lt;/SPAN&gt;    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; WaitForOutput() {
        m_affinity.Check();
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;while&lt;/SPAN&gt; (!CheckForInput()) {
            m_event.WaitOne();
        }
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; T GetNextOutput() {
        m_affinity.Check();
        T data;
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;while&lt;/SPAN&gt; (!TryGetOutput(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;out&lt;/SPAN&gt; data)) {
            m_event.WaitOne();
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; data;
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; TryGetOutput(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;out&lt;/SPAN&gt; T value) {
        m_affinity.Check();
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (CheckForInput()) {
            value = m_readerStack.Peek();
            m_readerStack = m_readerStack.Pop();
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;true&lt;/SPAN&gt;;
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;else&lt;/SPAN&gt; {
            value = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;default&lt;/SPAN&gt;(T);
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;false&lt;/SPAN&gt;;
        }
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; CheckForInput() {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (m_readerStack.IsEmpty) {
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; prev = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Interlocked&lt;/SPAN&gt;.Exchange(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;ref&lt;/SPAN&gt; m_writerStack, &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ImmutableStack&lt;/SPAN&gt;&amp;lt;T&amp;gt;.Empty);
            m_readerStack = prev.Reverse();
        }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; !m_readerStack.IsEmpty;
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AddInput(T value) {
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; done;
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;do&lt;/SPAN&gt; {
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; (m_inputClosed) {
                &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;throw&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;InvalidOperationException&lt;/SPAN&gt;(&lt;SPAN style="COLOR: rgb(163,21,21)"&gt;"Input end of pipe is closed"&lt;/SPAN&gt;);
            }
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; originalStack = m_writerStack;
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; newStack = originalStack.Push(value);
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; currentStack = &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Interlocked&lt;/SPAN&gt;.CompareExchange(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;ref&lt;/SPAN&gt; m_writerStack, newStack, originalStack);
            done = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;object&lt;/SPAN&gt;.ReferenceEquals(currentStack, originalStack);
        } &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;while&lt;/SPAN&gt; (!done);
        m_event.Set();
    }
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; CloseInput() {
        m_inputClosed = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;true&lt;/SPAN&gt;;
    }&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;[1] If you haven't read this series you really should.&amp;nbsp; &lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7996040" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category></item><item><title>Tuples Part 7: Mutable Tuples</title><link>http://blogs.msdn.com/jaredpar/archive/2008/01/23/tuples-part-7-mutable-tuples.aspx</link><pubDate>Wed, 23 Jan 2008 10:56:19 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7206269</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7206269.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7206269</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7206269</wfw:comment><description>&lt;p&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/01/22/tuples-part-6-comparing.aspx"&gt;Part 6&lt;/a&gt; left us with comparable tuples.&amp;#160; At this point, the Tuple class is functionally complete.&amp;#160; There will be a little more done with the debugability and overall fit into larger projects.&amp;#160; But otherwise it is sound.&amp;#160; &lt;/p&gt;  &lt;p&gt;Now the focus shifts to generating mutable tuples.&amp;#160; Immutability is nice for threading, memoization, etc ...&amp;#160; However it's not always practical to use immutable objects.&amp;#160; Often an algorithm does not benefit from immutability and lends itself to a more mutable type.&amp;#160; &lt;/p&gt;  &lt;p&gt;Mutable tuples behave like a Tuple in every other way except that they're ... mutable.&amp;#160; This includes implementing interfaces as well as inheritance structure.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;sealed&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;MutableTuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt; : 
    &lt;span style="color: rgb(43,145,175)"&gt;ITuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt;, 
    &lt;span style="color: rgb(43,145,175)"&gt;IEquatable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;MutableTuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt;&amp;gt;, 
    &lt;span style="color: rgb(43,145,175)"&gt;IComparable&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;MutableTuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt;&amp;gt;, 
    &lt;span style="color: rgb(43,145,175)"&gt;IComparable
&lt;/span&gt;{&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;As such the script already used will be sufficient to generate mutable classes in addition to the ones its already doing.&amp;#160; The majority of the code difference is just in the naming of the classes.&amp;#160; The only functional differences exist in the properties and indexer.&amp;#160; Both of these add a setter method.&amp;#160; Below is the modified code for generating the property and indexer.&amp;#160; &lt;/p&gt;

&lt;p&gt;function script:Gen-TupleAccess
  &lt;br /&gt;{

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; param ( [int] $count = $(throw &amp;quot;Need a count&amp;quot;), [bool]$mutable )

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;quot;public int Count { get { return $count; } }&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;quot;public object this[int index] { get { switch (index){ &amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; 0..($count-1) | %{ &amp;quot;case $($_): return m_$($lowerList[$_]);&amp;quot; }

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;quot;default: throw new InvalidOperationException(&amp;quot;&amp;quot;Bad Index&amp;quot;&amp;quot;);&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;quot;} }&amp;quot; &lt;/p&gt;

&lt;p&gt;&amp;#160;&amp;#160;&amp;#160; if ( $mutable )
  &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;quot;set { switch (index) {&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0..($count-1) | %{ &amp;quot;case $($_): m_$($lowerList[$_]) = (T$($upperList[$_]))value; break;&amp;quot; }

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;default: throw new InvalidOperationException(&amp;quot;&amp;quot;Bad Index&amp;quot;&amp;quot;);&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;} } &amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;quot;}&amp;quot;

  &lt;br /&gt;}&lt;/p&gt;

&lt;p&gt;function script:Gen-Property
  &lt;br /&gt;{

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; param ( [int] $index&amp;#160; = $(throw &amp;quot;Need an index&amp;quot;), [bool]$mutable = $false) &lt;/p&gt;

&lt;p&gt;&amp;#160;&amp;#160;&amp;#160; if (-not $mutable )
  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {

  &lt;br /&gt;@&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private readonly T{0} m_{1};

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public T{0} {0} {{ get {{ return m_{1}; }} }} &lt;/p&gt;

&lt;p&gt;&amp;quot;@ -f $upperList[$index],$lowerList[$index]
  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; else

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {

  &lt;br /&gt;@&amp;quot;

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; private T{0} m_{1};

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; public T{0} {0} {{ get {{ return m_{1}; }} set {{ m_{1} = value; }} }} &lt;/p&gt;

&lt;p&gt;&amp;quot;@ -f $upperList[$index],$lowerList[$index]
  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }

  &lt;br /&gt;}&lt;/p&gt;

&lt;p&gt;Now creating a mutable tuple is the same as the immutable tuple with just a name tweak.&lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; t1 = &lt;span style="color: rgb(43,145,175)"&gt;MutableTuple&lt;/span&gt;.Create(&lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;, 42);
            t1.A = &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;again&amp;quot;&lt;/span&gt;;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7206269" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Tuple/default.aspx">Tuple</category></item><item><title>Tuples Part 1</title><link>http://blogs.msdn.com/jaredpar/archive/2008/01/03/tuples-part-1.aspx</link><pubDate>Thu, 03 Jan 2008 19:25:51 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:6969362</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/6969362.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=6969362</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=6969362</wfw:comment><description>&lt;p&gt;A tuple in computer science can be described as a set of name/value pairs.&amp;nbsp; In some cases it can be described as simply a set of values that are accessible via an index [1].&amp;nbsp; Previously I discussed how to create a &lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/11/29/tuples-in-powershell.aspx"&gt;Tuple inside of PowerShell&lt;/a&gt;.&amp;nbsp; This series will focus on the use of Tuples in DotNet and how to use PowerShell to generate DotNet code.&amp;nbsp; &lt;/p&gt; &lt;p&gt;This series will also distinguish between mutable and immutable tuples.&amp;nbsp; As DotNet is shifting it's focus on parallel programming, immutable types are becoming more important.&amp;nbsp; Therefore this serious will focus on Tuples as immutable types and later examine mutable tuples.&lt;/p&gt; &lt;p&gt;In Visual Studio 2005, both C# and VB acquired tuples as a part of the programming language in the form of Anonymous Types.&amp;nbsp; These fit all of the properties of a tuple.&amp;nbsp; The one difference is in VB, anonymous types are mutable by default.&amp;nbsp; This can be changed though by using the &lt;strong&gt;Key&lt;/strong&gt; keyword.&amp;nbsp; &lt;/p&gt; &lt;p&gt;However anonymous types are lacking one quality which severely lessens their usefulness.&amp;nbsp; &lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/10/01/casting-to-an-anonymous-type.aspx"&gt;Their type cannot be described&lt;/a&gt;.&amp;nbsp; This prevents them from being used as parameters, fields, generic parameters [2] etc ...&amp;nbsp; Unless you use late binding or terribly awkward casts this is limiting.&amp;nbsp; &lt;/p&gt; &lt;p&gt;To get around this, we will be defining a set of generic tuple class supporting 1-N name value pairs.&amp;nbsp; The great downside is because we will be predefining these types the names in the name value pair will be fixed.&amp;nbsp; We will be using A-N for 1-N pairs. &lt;/p&gt; &lt;p&gt;This is very limiting in itself because it's reducing the expressiveness of a type.&amp;nbsp; Anonymous types are much more expressive since they have names.&amp;nbsp; Now types will have properties A,B, etc ...&amp;nbsp; &lt;/p&gt; &lt;p&gt;For me this still works.&amp;nbsp; In my code, I only end up using tuples when I need to pass data around between tightly coupled classes, or just within the same class.&amp;nbsp;&amp;nbsp; Since the creation and use are so close loosing the full expressiveness of the name is not that limiting.&amp;nbsp; &lt;/p&gt; &lt;p&gt;In addition, our tuple implementation will leverage type inference as much as possible such that the following code can be written.&lt;/p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple = &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;.Create(&lt;span style="color: rgb(163,21,21)"&gt;"foo"&lt;/span&gt;);
            &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(tuple.A);&lt;/pre&gt;
&lt;p&gt;Why write a script to generate these classes?&amp;nbsp; Wouldn't it just be easier to just do this by hand???&amp;nbsp; Yes and no.&amp;nbsp; If you are doing a fixed set of short used classes then yes, do it by hand.&amp;nbsp; These scripts evolved out of my use of tuples.&amp;nbsp; Once I would settle on a structure and I would think of a new feature I needed.&amp;nbsp; Typically I have tuples defined up to 5 fields.&amp;nbsp; Retyping out a new feature got tiresome and error prone.&amp;nbsp; With a scripting solution I could add a new feature and tests in just a few minutes.&amp;nbsp; The series is very representative of the way my solution changed over time.&amp;nbsp; Simple at first but I added features as the situation dictated.&amp;nbsp; Having a scripting solution saved me a lot of time.&lt;/p&gt;
&lt;p&gt;Next up, generating the basic structure.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;[1] In this case, the index just becomes the name and hence a name/value pair. &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=6969362" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/PowerShell/default.aspx">PowerShell</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Tuple/default.aspx">Tuple</category></item></channel></rss>