<?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 : C#</title><link>http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx</link><description>Tags: C#</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Making F# type inference friendly for C#</title><link>http://blogs.msdn.com/jaredpar/archive/2009/12/15/making-f-type-inference-friendly-for-c.aspx</link><pubDate>Tue, 15 Dec 2009 19:53:08 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9937228</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9937228.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9937228</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9937228</wfw:comment><description>&lt;p&gt;One of my current hobby projects, &lt;a href="http://blogs.msdn.com/jaredpar/archive/2009/12/14/vsvim-update-released-version-0-5-4.aspx"&gt;VsVim&lt;/a&gt;, requires me to make a lot of calls between F# and C# projects.&amp;#160; The core Vim engine is a pure F# solution based on Visual Studio’s new editor.&amp;#160; It additionally has a small hosting layer and a large test bed both written in C#.&amp;#160; &lt;/p&gt;  &lt;p&gt;When working with the exposed core Vim engine API, I’ve found a number of generated F# constructs which are not easily accessible from C#.&amp;#160; The problem stems from the manner in which native F# types are exposed.&amp;#160; Many of them are generic and&amp;#160; lack type inference friendly helper methods that force awkward usage patterns in C#.&amp;#160; Most painful is the FSharpOption&amp;lt;T&amp;gt; type because it’s a type I frequently expose in APIs.&amp;#160; &lt;/p&gt;  &lt;p&gt;FSharpOption&amp;lt;T&amp;gt; is the exposed type for the native F# &lt;a href="http://msdn.microsoft.com/en-us/library/dd233245(VS.100).aspx"&gt;option&lt;/a&gt; construct representing a value which may or may not be present. It’s similar to C#’s nullable type except that it applies to all types of values.&amp;#160; The primary operations you want to do with an FSharpOption&amp;lt;T&amp;gt; are &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Create an option with a value &lt;/li&gt;    &lt;li&gt;Create an option without a value &lt;/li&gt;    &lt;li&gt;Determine if it has a value &lt;/li&gt;    &lt;li&gt;Determine if it does not have a value &lt;/li&gt;    &lt;li&gt;Access the value &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;In F# using an option is an inherent part of the language and the hence the resulting code is very elegant. &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;OptionExample = 
    &lt;span style="color: blue"&gt;let &lt;/span&gt;optionWithValue = Some(&lt;span style="color: brown"&gt;42&lt;/span&gt;)
    &lt;span style="color: blue"&gt;let &lt;/span&gt;optionWithoutValue = None
    &lt;span style="color: blue"&gt;let &lt;/span&gt;isSome = Option.isSome optionWithValue
    &lt;span style="color: blue"&gt;let &lt;/span&gt;isNone = Option.isNone optionWithoutValue
    Option.get optionWithValue&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Unfortunately the equivalent C# code is not nearly so nice.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static int &lt;/span&gt;OptionExample() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;optionWithValue = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color: brown"&gt;42&lt;/span&gt;);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;optionWithoutValue = &lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.None;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;isSome = &lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.get_IsSome(optionWithValue);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;isNone = &lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.get_IsNone(optionWithValue);
    return optionWithValue.Value;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Too many explicit types!!!&amp;#160; Using any explicit type with F# related code just feels wrong.&amp;#160; &lt;/p&gt;

&lt;p&gt;In C#, and most other .Net languages, 4 out of the 5 operations you want to do on FSharpOption require an explicit type parameter.&amp;#160; This resulting code is a bit tedious with a simple type like int but once you get to more complex generics it can get extremely verbose.&amp;#160; In the case of anonymous types, it’s simply not possible to use the FSharpOption&amp;lt;T&amp;gt; without a few wrappers.&amp;#160; &lt;/p&gt;

&lt;p&gt;Luckily most of these can be solved by using the familiar pattern of using a non-generic class with static generic methods.&amp;#160; These allow C# users to take advantage of the languages type inference capabilities to reduce the verbosity of the code.&amp;#160; &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;FSharpOption &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt; Create&amp;lt;T&amp;gt;(T value) {
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt;(value);
    }
    &lt;span style="color: blue"&gt;public static bool &lt;/span&gt;IsSome&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt; opt) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt;.get_IsSome(opt);
    }
    &lt;span style="color: blue"&gt;public static bool &lt;/span&gt;IsNone&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt; opt) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt;.get_IsNone(opt);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now we can rewrite the original sample a bit cleaner &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static int &lt;/span&gt;OptionExample() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;optionWithValue = &lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;.Create(&lt;span style="color: brown"&gt;42&lt;/span&gt;);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;optionWithoutValue = &lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.None;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;isSome = optionWithValue.IsSome();
    &lt;span style="color: blue"&gt;var &lt;/span&gt;isNone = optionWithoutValue.IsNone();
    &lt;span style="color: blue"&gt;return &lt;/span&gt;optionWithValue.Value;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Notice we still haven’t fixed the None case.&amp;#160; Fixing this is a beyond the scope of what I want to write here but it is possible in certain scenarios.&amp;#160; You can take a look at how in one of my previous blog articles: &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/10/06/functional-c-providing-an-option.aspx"&gt;Function C# Providing an Option&lt;/a&gt;.&amp;#160; &lt;/p&gt;

&lt;p&gt;This pattern is not just limited to the FSharpOption class but can be applied to many of the generic constructs F# exports to wrap their native types.&amp;#160; In particular FSharpFunc&amp;lt;T,Result&amp;gt; and the various FSharpChoice&amp;lt;&amp;gt; types can be made a bit friendlier with a few wrappers.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9937228" 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/Type+Inference/default.aspx">Type Inference</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/F_2300_/default.aspx">F#</category></item><item><title>The File System is unpredictable</title><link>http://blogs.msdn.com/jaredpar/archive/2009/12/10/the-file-system-is-unpredictable.aspx</link><pubDate>Thu, 10 Dec 2009 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9934789</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>11</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9934789.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9934789</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9934789</wfw:comment><description>&lt;p&gt;One of the more frequent questions I answer on StackOverflow is a variation of the following.&amp;#160; &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;I’m doing XXX with a file, how can I know if the file exists?&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The variations include verify no one else has the file open, if the file is in use, the file is not writable, etc ….&amp;#160; The answer to all of these questions is unfortunately the same.&amp;#160; Simply put you can’t.&amp;#160; The reason why is the fundamental nature of the file system prevents such predictive operations.&amp;#160; &lt;/p&gt;  &lt;p&gt;The file system is a resource with multiple levels of control that is shared between all users and processes in the system.&amp;#160; The levels of control include but are not limited to file system and sharing permissions.&amp;#160; At &lt;strong&gt;any&lt;/strong&gt; point in time any entity on the computer may change a file system object or it’s controls in any number of ways.&amp;#160; For example &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The file could be deleted &lt;/li&gt;    &lt;li&gt;A file could be created at place one previously did not exist &lt;/li&gt;    &lt;li&gt;Permissions could change on the file in such a way that the current process does not have access &lt;/li&gt;    &lt;li&gt;Another process could open the file in such a way that is not conducive to sharing &lt;/li&gt;    &lt;li&gt;The user remove the USB key containing the file &lt;/li&gt;    &lt;li&gt;The network connection to the mapped drive could get disconnected &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Or in short &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The file system is best viewed as a multi-threaded object over which you have no reliable synchronization capabilities&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Many developers, and APIs for that matter, though treat the file system as though it’s a static resource and assume what’s true at one point in time will be true later.&amp;#160; Essentially using the result of one operation to predict the success or failure of another.&amp;#160; This ignores the possibility of the above actions interweaving in between calls.&amp;#160; It leads to code which reads well but executes badly in scenarios where more than one entity is changing the file system. &lt;/p&gt;  &lt;p&gt;These problems are best demonstrated by a quick sample.&amp;#160; Lets keep it simple and take a stab at a question I’ve seen a few times.&amp;#160; The challenge is to write a function which returns all of the text from a file if it exists and an empty string if it does not.&amp;#160; To simplify this problem lets assume permissions are not an issue, paths are properly formatted, paths point to local drives and people aren’t randomly ripping out USB keys.&amp;#160; Using the System.IO.File APIs we may construct the following solution.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static string &lt;/span&gt;ReadTextOrEmpty(&lt;span style="color: blue"&gt;string &lt;/span&gt;path) {
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;File&lt;/span&gt;.Exists(path)) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;File&lt;/span&gt;.ReadAllText(path); &lt;span style="color: green"&gt;// Bug!!!
    &lt;/span&gt;} &lt;span style="color: blue"&gt;else &lt;/span&gt;{
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;String&lt;/span&gt;.Empty;
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This code reads great and at a glance looks correct but is actually fundamentally flawed.&amp;#160; The reason why is the code changes depends on the call to File.Exist to be true for a large portion of the function.&amp;#160; It’s being used to predict the success of the call to ReadAllText.&amp;#160; However there is nothing stopping the file from being deleted in between these two calls.&amp;#160; In that case the call to File.ReadAllText would throw a FileNotFoundException which is exactly what the API is trying to prevent! &lt;/p&gt;

&lt;p&gt;This code is flawed because it’s attempting to use one piece of data to make a prediction about the future state of the file system.&amp;#160; This is simply not possible with the way the file system is designed.&amp;#160; It’s a shared resource with no reliable synchronization mechanism.&amp;#160; File.Exists is much better named as File.ExistedInTheRecentPast (the name gets much worse if you consider the impact of permissions).&amp;#160; &lt;/p&gt;

&lt;p&gt;Knowing this, how could we write ReadTextOrEmpty in a reliable fashion?&amp;#160; Even though you can not make predictions on the file system the failures of operations is a finite set.&amp;#160; So instead of attempting to predict successful conditions for the method, why not just execute the operation and deal with the consequences of failure?&amp;#160;&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static string &lt;/span&gt;ReadTextOrEmpty(&lt;span style="color: blue"&gt;string &lt;/span&gt;path) {
    &lt;span style="color: blue"&gt;try &lt;/span&gt;{
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;File&lt;/span&gt;.ReadAllText(path);
    } &lt;span style="color: blue"&gt;catch &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;DirectoryNotFoundException&lt;/span&gt;) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;String&lt;/span&gt;.Empty;
    } &lt;span style="color: blue"&gt;catch &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;FileNotFoundException&lt;/span&gt;) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;String&lt;/span&gt;.Empty;
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This implementation provides the original requested behavior.&amp;#160; In the case the file exists, for the duration of the operation, it returns the text of the file and if not returns an empty string.&amp;#160; &lt;/p&gt;

&lt;p&gt;In general I find the above pattern is the best way to approach the file system.&amp;#160; Do the operations you want and deal with the consequences of failure in the form of exceptions.&amp;#160; To do anything else involves an unreliable prediction in which you still must handle the resulting exceptions.&amp;#160; &lt;/p&gt;

&lt;p&gt;If this is the case then why have File.Exist at all if the results can’t be trusted?&amp;#160; It depends on the level of reliability you want to achieve.&amp;#160; In production programs I flag any File.Exist I find as a bug because reliability is a critical component.&amp;#160; However you’ll see my personal powershell configuration scripts littered with calls to File.Exsit.&amp;#160; Simply put because I’m a bit lazy in those scripts because critical reliability is not important when I’m updating my personal .vimrc file.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9934789" 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/API+Design/default.aspx">API Design</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Exceptions/default.aspx">Exceptions</category></item><item><title>Using F# Discriminated Unions in C# (Beta2)</title><link>http://blogs.msdn.com/jaredpar/archive/2009/10/27/using-f-discriminated-unions-in-c-beta2.aspx</link><pubDate>Tue, 27 Oct 2009 12:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9913363</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9913363.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9913363</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9913363</wfw:comment><description>&lt;p&gt;While updating my VsVim editor extensions for Beta2 [1] I got hit by a change in the way F# exposed discriminated unions in metadata.&amp;#160; My extension consists of a core F# component with a corresponding set of unit tests written in C#.&amp;#160; It’s mostly API level testing and as such I use a lot of F# generated types in my C# test assembly.&lt;/p&gt;  &lt;p&gt;In Beta1 all information which could be extracted from a discriminated type union was immediately available on the value.&amp;#160; The underlying type presentation was less than desirable but these details were hidden by type inference and the very accessible API.&amp;#160;&amp;#160; The type wasn’t perfect because given a particular instance only the subset of the properties relevant to the union value type were valid.&amp;#160; All others threw exceptions.&amp;#160; But the code use of these methods and properties flowed very well.&amp;#160;&amp;#160; &lt;/p&gt;  &lt;p&gt;For instance take the following F# definition&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;ActionKind =
    | Mouse = &lt;span style="color: brown"&gt;1
    &lt;/span&gt;| Keyboard = &lt;span style="color: brown"&gt;2

&lt;/span&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;ActionResult =
    | Complete &lt;span style="color: blue"&gt;of &lt;/span&gt;(ActionKind * int)
    | Error &lt;span style="color: blue"&gt;of &lt;/span&gt;string
    | NeedMore &lt;span style="color: blue"&gt;of &lt;/span&gt;(char &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;ActionResult)&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The use case in C# was quite simple&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;TestActionBeta1(){
    &lt;span style="color: blue"&gt;var &lt;/span&gt;res = GetResult();
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(res.IsComplete());
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: #2b91af"&gt;ActionKind&lt;/span&gt;.Mouse, res.Complete1.Item1);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: brown"&gt;42&lt;/span&gt;, res.Complete1.Item2);
}&lt;/pre&gt;

&lt;p&gt;Notice how no type information is necessary and the code flows quite naturally.&amp;#160; C# type inference works great here and allows me to do what I need to do without fussing around with little stuff.&amp;#160; The type in this case is a detail I don’t need to know about.&amp;#160; It simply adds no value.&amp;#160; &lt;/p&gt;

&lt;p&gt;Discriminated Unions in Beta2 changed substantially in this area.&amp;#160; Instead of generating the set of all values on the exposed type, there is now an inner type generated for every discriminated union value and the properties relevant to that union value are stored on the inner type.&amp;#160; The outer type now contains only properties to determine which type of value it is (certainly an upgrade from methods!) [2]&lt;/p&gt;

&lt;p&gt;For instance in the case of ActionResult there are 3 generated inner classes: Complete, Error and NeedMore.&amp;#160; Each one contains a single property Item which contains the associated value(s).&amp;#160; This means to get to the value portion a cast to the inner type must be inserted!&amp;#160; &lt;/p&gt;

&lt;p&gt;Lets take a a look at how the above test code has to change to deal with the Beta2 generation of ActionResult.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;TestActionBeta2() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;res = GetResult();
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(res.IsComplete);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: #2b91af"&gt;ActionKind&lt;/span&gt;.Mouse, ((&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete&lt;/span&gt;)res).Item.Item1);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: brown"&gt;42&lt;/span&gt;, ((&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete&lt;/span&gt;)res).Item.Item2);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Notice the explicit casts which must be added to access the values.&amp;#160; This makes it impossible to rely soley on C# type inference.&amp;#160; I must now understand the underlying type structure of discriminated unions in order to use them.&amp;#160; This extra cast adds no real value to my code.&amp;#160; &lt;/p&gt;

&lt;p&gt;My C# test assembly has literally hundreds of test cases which use this pattern on F# types.&amp;#160; I didn’t know the return type of every method and found myself hitting “Goto Def” on a lot of “var” instances to discover the static type, going back to the original file and inserting the cast.&amp;#160; It was a tedious and slow process.&lt;/p&gt;

&lt;p&gt;Eventually I settled on a different solution.&amp;#160; For every type I exposed in F# I added a set of extension methods in the form of AsXXX where XXX represented the name of the generated inner types.&amp;#160;&amp;#160; For example&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete &lt;/span&gt;AsComplete(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult &lt;/span&gt;res) {
    &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete&lt;/span&gt;)res;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The advantage of this approach is 2 fold &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Removes the need to explicitly name types in code and hence gets back the advantages of type inference&lt;/li&gt;

  &lt;li&gt;I can now use . on any of the values and let Intellisense help me find the appropriate method to use&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This extension method allows me to get closer to the Beta1 style code &lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;TestActionBeta2() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;res = GetResult();
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(res.IsComplete);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: #2b91af"&gt;ActionKind&lt;/span&gt;.Mouse, res.AsComplete().Item.Item1);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: brown"&gt;42&lt;/span&gt;, res.AsComplete().Item.Item2);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;With these methods and a quick series of Find / Replace calls, I was back in business.&amp;#160; &lt;/p&gt;

&lt;p&gt;[1] It’s coming I promise!&amp;#160; &lt;/p&gt;

&lt;p&gt;[2] It also contains a handy set of factory methods for generating values but it’s not relevant to this discussion.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9913363" 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/Extension+Methods/default.aspx">Extension Methods</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/F_2300_/default.aspx">F#</category></item><item><title>Why is LINQ absent from debugger windows?</title><link>http://blogs.msdn.com/jaredpar/archive/2009/08/26/why-no-linq-in-debugger-windows.aspx</link><pubDate>Wed, 26 Aug 2009 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9877055</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9877055.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9877055</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9877055</wfw:comment><description>&lt;p&gt;As the owner of the VB.Net portion of the overall debugging experience, I frequently hear the request from customers to add LINQ support into the Watch / Immediate and Locals window.&amp;nbsp; Virtually every other type of expression is available in the debugger windows so why leave one of the most popular ones out? &lt;/p&gt;  &lt;p&gt;Quick Diversion: the specifics of this article are written from the point of view of the VB.Net expression evaluator.&amp;nbsp; However, the limitations blocking LINQ support (in both the architecture and overall design) are very similar between VB.Net and C#.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;As usual, the primary issue is cost and the cost for LINQ in the debugger windows is very high.&amp;nbsp; To understand why the cost is so high though, we must start by getting a better understanding how a language service interacts with the debugging services of Visual Studio and the general philosophy around compiler features in the debugger.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Languages in Visual Studio typically provide the following major components to support the debugging experience.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;     &lt;p&gt;Expression Evaluator (EE): This is the language specific component which provides all of the data used in the watch, locals and immediate window, data tips, conditional breakpoints and several other components.&amp;nbsp; It’s primary input is an expression in string form which is converted to a value (typically an ICorDebugValue instance) and outputs a COM object capable of inspecting that value to the core debugger [1].&amp;nbsp;&amp;nbsp; Everything typed into the debugger windows goes through the EE.&lt;/p&gt;      &lt;p&gt;This component lives in the MTA of Visual Studio and has almost no interaction with the UI / STA thread. &lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;ENC Service: This is the component which is the work horse of ENC operations.&amp;nbsp; It provides rude edit detection, metadata differencing and metadata + IL generation&amp;nbsp;&amp;nbsp; .&lt;/p&gt;      &lt;p&gt;This component lives in the main STA of Visual Studio&lt;/p&gt;   &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The important thing to understand about the expression evaluator is that it’s purpose is primarily to provide an expression evaluation and data inspection service.&amp;nbsp; How expression evaluation works is an article in itself but suffice it to say that it converts the string to a very low level AST then walks the nodes bottom up and evaluating the expressions using the ICorDebug APIs.&amp;nbsp; The EE component has no UI and is simply a data provider for the core debugger services.&amp;nbsp;&amp;nbsp; &lt;/p&gt;  &lt;p&gt;The design philosophy for Both VB.Net and C# is to have the highest level of fidelity between expressions evaluated in the EE and the actual running program.&amp;nbsp; To do otherwise would lead to extremely confusing results for users.&amp;nbsp; When spec’ing feature support in the VB.Net EE we start from the point of 100% fidelity, determine the problems with this design (if any) and then start the difficult process of making compromises.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;LINQ expressions are very different than any other expression previously allowed in the EE window because of the features interaction with metadata.&amp;nbsp; All LINQ expressions require the generation or manipulation of metadata to support the underlying lambda and/or closure.&amp;nbsp; Adding support for this is one of the biggest hurdles to getting LINQ (and other features) into the EE.&amp;nbsp;&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Evaluating a LINQ expression is actually much closer to an ENC operation than a traditional EE one.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Currently the EE’s have no capacity for generating metadata, only interpreting it.&amp;nbsp; Operations which mutate or generate metadata have traditionally only been allowed via the ENC service.&amp;nbsp; Getting LINQ to work in the EE with true fidelity would require at least a minimal amount of ENC feature work.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Without getting into too much detail, lets enumerate the&lt;b&gt; new&lt;/b&gt; major features necessary to evaluate a LINQ expression in the EE with true fidelity to the running program.&amp;nbsp; To simplify things, we’ll start by assuming there is no other LINQ expression used in the current method and the method is only being executed at most once at any given time in the process.&amp;nbsp;&amp;nbsp; &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;A metadata generation service to support the backing for closures and lambda expressions &lt;/li&gt;    &lt;li&gt;Convert expressions typed in the EE into IL [2] &lt;/li&gt;    &lt;li&gt;ENC support for metadata to push the new metadata for closures and lambdas into the currently executing assembly &lt;/li&gt;    &lt;li&gt;ENC support for method body IL to remove lifted variables from the current method and redirect the references inside the closure&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Issues #1 and #2 are for the most part internal architecture issues and can be solved via normal processes of code base refactoring and adding new features to an existing component.&amp;nbsp;&amp;nbsp; I don’t mean to imply these problems are cheap (in fact they are relatively expensive)&amp;nbsp; But fixing these is somewhat of an understood quantity.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Issues #3 and #4 are where the problems start.&amp;nbsp; As implemented EE’s do not have capability to create or modify metadata in the running process (that is the job of the ENC service).&amp;nbsp; EE’s do have access to the underlying CLR ENC APIs so it is possible to implement ENC operations in the EE.&amp;nbsp; It’s just simply not been done yet.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Wait!&amp;nbsp; Why not reuse our ENC implementation in the EE?&amp;nbsp; Unfortunately the ENC service is currently tied heavily to our in memory IDE compiler and many other IDE / STA features.&amp;nbsp; It in fact lives in a completely separate DLL, separate COM apartment and works on a different symbol table than the EE.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;More fundamental though is that it’s designed for a completely different purpose.&amp;nbsp; ENC is designed to track edits in live code, determining the differences and applying them to the running program.&amp;nbsp; The hypothetical EE feature would be tracking expressions that modify a running DLL for which code is not guaranteed (and not likely) to be available and applying the difference to the running program.&amp;nbsp; There are some similarities but the differences are significant enough to make code reuse have limited value.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Some people may wonder why it’s necessary to implement #4.&amp;nbsp; Couldn’t we just avoid removing the variable from the current method and make the feature cheaper?&amp;nbsp; This is possible but it would cause a significant fidelity difference in the feature.&amp;nbsp; Any mutations of the local variable within the LINQ expression would not be visible on the stack frame as it would if the LINQ expression was present in the original program.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;It’s easy to think of this ENC in the EE as just the same type of cost as #1 and #2 (in many ways it is).&amp;nbsp; However taking advantage of the CLR ENC APIs in the EE also means that we inherit it’s limitations as well.&amp;nbsp; ENC as as implemented in the CLR has many limitations which fly in the face of LINQ.&amp;nbsp; In particular the following ENC limitations present major problems (&lt;a mce_href="http://blogs.msdn.com/jmstall/archive/2005/02/19/376666.aspx" href="http://blogs.msdn.com/jmstall/archive/2005/02/19/376666.aspx"&gt;ENC limitations reference&lt;/a&gt;).&amp;nbsp; &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Cannot add members to a value type.&amp;nbsp; This prevents evaluating LINQ when stopped in a value type method &lt;/li&gt;    &lt;li&gt;Cannot remove locals from a function.&amp;nbsp; This is an implementation of LINQ but we could work around this problem by changing the IL to simply no longer accessing the local variables. &lt;/li&gt;    &lt;li&gt;Cannot change anything in a generic type.&amp;nbsp; This prevents evaluating LINQ when stopped in a generic type.&amp;nbsp; &lt;/li&gt;    &lt;li&gt;Cannot specify an initial value for newly added fields. &lt;/li&gt;    &lt;li&gt;Allowable ENC operations differ between the top of the stack and operations elsewhere within the stack &lt;/li&gt;    &lt;li&gt;Modification of a non-top stack frame cannot significantly edit the current function call.&amp;nbsp; So if a LINQ expression captures a variable used in that call (think ref passing) it would likely be unable to be evaluated.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;So even if we implemented everything possible on the language service side the resulting feature would be limited in several impactful ways.&amp;nbsp; Additionally these limitations are somewhat orthogonal to the current limitations EE’s face and would require a bit of user education.&amp;nbsp; And this is only for the most basic LINQ feature under unrealistic scenarios.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Lets now consider the problems of evaluating a LINQ expression when the current method already contains a LINQ expression that lifts at least 1 variable.&amp;nbsp; Evaluating a new expression at the same scope would require the modification of the current closure to maintain fidelity as opposed to generating a new one.&amp;nbsp; This brings along with it a couple more problems.&amp;nbsp; &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;     &lt;p&gt;A lambda expression which uses 2 variables, 1 of which is captured in an existing lambda expression.&amp;nbsp; To maintain fidelity we would have to modify an existing closure signature to contain the new variable. &lt;/p&gt;      &lt;p&gt;&amp;nbsp;&lt;/p&gt;      &lt;p&gt;Often times generated closures are generic so we would run straight into ENC limitation #3. Additionally we would need the newly added field to have the same value as it has in the current method which runs us into ENC limitation #4. Now also consider that a closure instance can live much longer than the method in which it was created. For those closures no stack value is available so what value should we give fields in that instance?&amp;nbsp; Ideally it should have the value of the variable at the point the method exited but realistically that’s not possible.&amp;nbsp; &lt;/p&gt;      &lt;p&gt;&amp;nbsp;&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;A lambda expression which uses 1 variable in a method where an existing lambda expression captures that same variable and another.&amp;nbsp; To maintain fidelity we would have to know about this and fake capture the second variable as well.&lt;/p&gt;   &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Now consider all of the problems above and consider the scenario where there are multiple threads and multiple instances of the current method active in the program.&amp;nbsp; How to determine which closure instance belongs to which thread, and just as important which stack frame on which thread, with respect to initializing values?&lt;/p&gt;  &lt;p&gt;None of the issues are an unsolvable problem but they do represent a significant cost to the feature.&amp;nbsp; And once again even if we added all of these features to the EE, ENC limitations would significantly limit the usefulness of the resulting feature.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Does this mean that LINQ, or any future metadata requiring expression, will never be added to the debugger window?&amp;nbsp; Absolutely not.&amp;nbsp; We’ve just hit the difficult stage of making compromises on the level of fidelity in the feature.&amp;nbsp; If you back off of true fidelity in a few small ways the resulting feature, while still very expensive, is significantly cheaper and removes many of the limitations imposed by ENC.&amp;nbsp;&amp;nbsp; This &lt;b&gt;hypothetical&lt;/b&gt; feature will be discussed in my next article.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;[1] For those interested the returned interface is &lt;a mce_href="http://msdn.microsoft.com/en-us/library/bb161287(VS.80).aspx" href="http://msdn.microsoft.com/en-us/library/bb161287(VS.80).aspx"&gt;IDebugProperty2&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;[2] Right now expressions are converted to a tree form slightly above IL and they are interpreted using the ICorDebug APIs.&amp;nbsp; Converting all the way down to IL requires a lot more work&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9877055" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx">Closures</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/Debugging/default.aspx">Debugging</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Lambda/default.aspx">Lambda</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/LINQ/default.aspx">LINQ</category></item><item><title>Understanding the is, was and will of programming</title><link>http://blogs.msdn.com/jaredpar/archive/2009/04/27/understanding-the-is-was-and-will-of-programming.aspx</link><pubDate>Mon, 27 Apr 2009 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9569623</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9569623.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9569623</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9569623</wfw:comment><description>&lt;p&gt;When using an API you must take care to understand not only what it returns, but also for how long the data returned will be valid.&amp;#160; This is very important to consider because programs must make either be making decisions on valid and predictable data or have appropriate fallback mechanisms for failure.&amp;#160; &lt;/p&gt;  &lt;p&gt;I often find bugs because people assumed certain APIs were giving back data about the present or future, but in fact the were giving back information about the past or much shorter present.&amp;#160; Part of the problem stems from the fact that API names are usually written in the present tense regardless of what point in time the data returned is valid.&amp;#160; For example “Exists” instead of “Existed” or “DidExist”.&amp;#160; The language of the API lulls developers into a false sense of security and leads to programming errors.&amp;#160; &lt;/p&gt;  &lt;p&gt;I like to think of these values as a question of when they are valid.&amp;#160; For instance, the data is, was or will be valid. &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Will – The data return is valid now and will be valid for the remainder of the program.&amp;#160; &lt;/li&gt;    &lt;li&gt;Is – The data is valid now and will remain valid until the program or thread takes some action to alter the underlying data source. &lt;/li&gt;    &lt;li&gt;Was – The data was valid at some point in the past but by the time the program receives the result it can no longer be relied upon to be valid. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Working with APIs in the “was” category are the trickiest.&amp;#160; Because the data we are working with is volatile we must approach them in a different way in order to provide reliable programs.&amp;#160; Most algorithms work by validating the present or future state of the system and then executing code with the expectation of success.&amp;#160; When working with a “was” API, there is no way validate the state of system because it cannot provide reliable information about its present or future state.&amp;#160; Instead we must execute the algorithm with the expectation of failure and spend our time considering how to account for these failures appropriately.&amp;#160; Failure must be the expected case, and not the exception.&lt;/p&gt;  &lt;p&gt;Working with “will” and “is” APIs is a bit easier.&amp;#160; Each has a level of predictability and it’s possible to use program state to make reliable decisions and hence produce reliable results.&lt;/p&gt;  &lt;p&gt;Lets add some substance to this conversation by considering these types of APIs and the ContainsKey method on various hashtable style collections.&amp;#160; This API is often written in the present tense regardless of how long the data is actually valid.&lt;/p&gt;  &lt;p&gt;A “will” API is the safest to work with because the data will always be valid.&amp;#160; This API cannot be influenced by side effects.&amp;#160; Hence the the programmer is free to think only about the algorithm at hand.&amp;#160; These APIs are rare and are typically associated with purely immutable data structures.&amp;#160; This is the main type of structure for which data does not ever change.&amp;#160; For instance consider this set of calls&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;name = &lt;span style="color: #a31515"&gt;&amp;quot;bob&amp;quot;&lt;/span&gt;;
&lt;span style="color: #2b91af"&gt;ImmutableMap&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Student&lt;/span&gt;&amp;gt; map = GetSomeImmutableMap();
&lt;span style="color: blue"&gt;if &lt;/span&gt;(map.ContainsKey(name)) {
    SomeOtherCall();
    &lt;span style="color: blue"&gt;var &lt;/span&gt;student = map[name];
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This call to the indexer will succeed no matter what.&amp;#160; The structure cannot be changed irrespective of what actually happens in SomeOtherCall.&amp;#160; The ContainsKey method already asserted the key was present in the hashtable.&amp;#160; Because the structure is immutable this assertion will be valid for the remainder of the program and hence the indexer must succeed.&lt;/p&gt;

&lt;p&gt;An “is” API is the most common type of API.&amp;#160; It is generally associated with mutable structures completely within the control of the program / thread.&amp;#160; The data will remain valid until it is explicitly, or much worse implicitly, invalidated by the user.&amp;#160; In a well factored program it is possible to reason about these types of APIs but hidden side effects can get you into trouble.&amp;#160; For instance consider the following code in the context of a single thread. &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;name = &lt;span style="color: #a31515"&gt;&amp;quot;bob&amp;quot;&lt;/span&gt;;
&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Student&lt;/span&gt;&amp;gt; map = GetSomeDictionary();
&lt;span style="color: blue"&gt;if &lt;/span&gt;(map.ContainsKey(name)) {
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(map[name]);
    SomeOtherCall();
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(map[name]);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The state of a Dictionary&amp;lt;TKey,TValue&amp;gt; structure is completely within the control of the program. As such the first call to Console.WriteLine will work fine.&amp;#160; There is nothing which can alter the state of map between the call to ContainsKey and the actual accessing of the map in the first WriteLine call so the assertion is still valid.&amp;#160; &lt;/p&gt;

&lt;p&gt;However without knowing the hidden side effects of the SomeOtherCall API we cannot know the next call to WriteLine will succeed.&amp;#160; It’s possible for SomeOtherCall to access the underlying Dictionary reference and Clear it thus making the next call fail.&amp;#160; True a programmer must investigate this before writing the above code.&amp;#160; But consider the opposite problem.&amp;#160; I am the maintainer of SomeOtherCall and I get a bug assigned to me which necessitates clearing out that Dictionary.&amp;#160; I must now consider everyone who calls me, directly or indirectly and consider if any of them have an implicit dependency on the state of the underlying Dictionary object.&amp;#160; This can get very difficult in a large program. &lt;/p&gt;

&lt;p&gt;As previously stated, a “was” API is the most dangerous type of API.&amp;#160; They never give back data for which you can make a reliable decision about.&amp;#160; These APIs are associated with a data source that is not completely in the control of the current thread or program.&amp;#160; Thus it’s possible for the data source to be altered at any point in the execution of the program / thread.&amp;#160; Threading is a prime example of this problem.&lt;/p&gt;

&lt;p&gt;For an example, consider SynchronizedDictionary to be an implementation of Dictionary&amp;lt;TKey,TValue&amp;gt; which uses locks internally to prevent data corruption from reads / writes on multiple threads but provides no other synchronization capabilities .&amp;#160; &lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;name = &lt;span style="color: #a31515"&gt;&amp;quot;bob&amp;quot;&lt;/span&gt;;
&lt;span style="color: #2b91af"&gt;SynchronizedDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Student&lt;/span&gt;&amp;gt; map = GetSomeSynchronizedDictionary();
&lt;span style="color: blue"&gt;if &lt;/span&gt;(map.ContainsKey(name)) {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;student = map[name];
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;In this example it’s possible for the call to map[name] to fail because another thread came through and cleared the collection in between the if statement and the call to map[name].&amp;#160; The bug here is that the program was written as if ContainsKey gave information about the present or future but in fact only gave information about the past.&amp;#160; This actual return of the API could be made clearer by simply altering the name of the API.&amp;#160; A much more applicable name is “DidContainKey” or “DidAndMayStillContainKey”.&amp;#160; This name is much more representative of the data returned and will hopefully give a developer pause before writing code like the above.&amp;#160; &lt;/p&gt;

&lt;p&gt;My personal pet peeve in this category is the file system and in particular &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx"&gt;File.Exists&lt;/a&gt;.&amp;#160; Notice how this name is written in the present tense indicating a successful return means the file is currently in existence.&amp;#160; Lets ignore permissions for a minute[1] and consider only the files existence.&amp;#160; Any program on the machine is at liberty to change the file system and can do so at any point in time.&amp;#160; Even the user can affect the file system by doing some thing as simple as yanking out a USB thumb drive or stumbling over a network cable.&amp;#160; Any of these operations can alter the state of the file system and hence invalidate the existence of a File with 0 action from your program.&amp;#160; Hence File.Exists cannot ever reliably determine if a file exists, it can only determine that a file “did” exist at some point in the past and may exist at some point in the future.&amp;#160; A more representative name would be File.DidExist, or File.DidAndMayStillExist.&amp;#160; &lt;/p&gt;

&lt;p&gt;So when designing your APIs, take care to consider the lifetime of the data when naming them.&amp;#160; &lt;/p&gt;

&lt;p&gt;[1] Once you consider permissions you find that even File.DidExist in not a representative name.&amp;#160; It probably should be called File.DidExistAndHadSomeMeasureOfAccess.&amp;#160; Yes, that’s a terrible name :(&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9569623" 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/API+Design/default.aspx">API Design</category></item><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>Is it Serializable?</title><link>http://blogs.msdn.com/jaredpar/archive/2009/03/31/is-it-serializable.aspx</link><pubDate>Tue, 31 Mar 2009 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9499985</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9499985.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9499985</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9499985</wfw:comment><description>&lt;p&gt;I’ve recently run across several APIs that have a dependency on only dealing with objects that are serializable (in the binary sense).&amp;#160; Unfortunately determining if an object is serializable is a non-trivial task and rife with problems.&amp;#160; These problems have a direct impact on the types of guarantees these APIs can make.&lt;/p&gt;  &lt;p&gt;For all objects which are serializable, it’s only possible to prove that a very small subset of them actually are in code.&amp;#160; Easier but less reliable tests are very easy to write.&amp;#160; So APIs must make a trade off.&amp;#160; Only accept instances of types which are provable serializable and miss out on a while class of objects.&amp;#160; Or do a much less reliable check and open themselves up to failure further down in the algorithm.&lt;/p&gt;  &lt;p&gt;Take System.Exception for example.&amp;#160; It is possible to associate arbitrary data with an exception through the &lt;a href="http://msdn.microsoft.com/en-us/library/system.exception.data.aspx"&gt;Data&lt;/a&gt; property.&amp;#160; Associated just any object with Exception is problematic though because Exceptions &lt;a href="http://winterdom.com/weblog/2007/01/16/MakeExceptionClassesSerializable.aspx"&gt;should be serializable&lt;/a&gt;.&amp;#160; In order for an Exception instance to store these objects and remain serializable, the objects must also be serializable.&amp;#160; Since serializability is not provable, the authors of Exception had to make a trade off between an overly restrictive test, or a loose test.&amp;#160; They chose the latter.&amp;#160; As a result it’s impossible to determine before hand if a given Exception instance is actually serializable.&amp;#160; &lt;/p&gt;  &lt;p&gt;Why is this the case though that serialization is tough to determine?&amp;#160; Lets start with what it takes to make a type serializable.&amp;#160; There are two separate components&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Declaring that the type is Serializable by either having the SerializableAttribute on the class definition or by implementing ISerializable &lt;/li&gt;    &lt;li&gt;Making the type conform to the rules of serialization.&amp;#160; &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;These are completely separate actions.&amp;#160; It’s possible to have types which do any combination of the above but not both.&amp;#160; Take for instance the following type declarations&lt;/p&gt;  &lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Serializable&lt;/span&gt;]
&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DeclaredOnly &lt;/span&gt;{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ConformsOnly &lt;/span&gt;m_conforms;
}

&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ConformsOnly &lt;/span&gt;{
    &lt;span style="color: blue"&gt;private string &lt;/span&gt;m_name;
}&lt;/pre&gt;

&lt;p&gt;Both of these types are legal C# code and both represent one of the two extremes listed above.&amp;#160; Yet neither of these types are actually serializable.&amp;#160; ConformsOnly is not because it has not actually declared itself to be serializable.&amp;#160; DeclaredOnly is not because one of it’s members is not serializable.&amp;#160; &lt;/p&gt;

&lt;p&gt;Lets look at proving serialization by ensuring types follow both of the rules.&amp;#160; Proving the first part of serialization is pretty straight forward.&amp;#160; Simply check to see if a type implements ISerializable or is decorated with the Serialization attribute.&amp;#160; The latter is directly supported in the type system via &lt;a href="http://msdn.microsoft.com/en-us/library/system.type.isserializable.aspx"&gt;Type.IsSerializable&lt;/a&gt;.&amp;#160; This property is also the source of the most common mistake I see with respect to determining if an object is serializable.&amp;#160; Take the following code snippet for an example.&lt;/p&gt;

&lt;p&gt;&lt;span style="color: blue"&gt;public static void&lt;/span&gt;Example1(&lt;span style="color: blue"&gt;object &lt;/span&gt;o) { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color: blue"&gt;if&lt;/span&gt;(o.GetType().IsSerializable) { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color: green"&gt;// Do something different 
    &lt;br /&gt;&amp;#160;&amp;#160; &lt;/span&gt;} 

  &lt;br /&gt;}&lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;On the surface, this looks like reasonable code.&amp;#160; But as we just pointed out, the property IsSerializable just determines the presence or absence of the Serializable attribute but nothing about the second part.&amp;#160; A more descriptive attribute name would be IsSerializableAttributeDeclared.&amp;#160; Yet many pieces of code attempt to equate this property with the ability to be serialized (A fun experiment here is to search for it’s use in Reflector)&lt;/p&gt;

&lt;p&gt;Proving the second part involves two cases, types implementing ISerializable and types decorated with the Serializable attribute.&amp;#160; Lets start with the attribute.&amp;#160; Proving these is involved but a straight forward process.&amp;#160; The type must …&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Be decorated with the Serializable Attribute &lt;/li&gt;

  &lt;li&gt;One of the following items must be true for every field at all points in the hierarchy 
    &lt;ol&gt;
      &lt;li&gt;It must be decorated with the NonSerializedAttribute &lt;/li&gt;

      &lt;li&gt;The type of the field must be sealed and must conform to all of these rules &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Instances of types which meet these guidelines will always be serializable.&amp;#160; Not meeting these rules though does not exclude a type from serialization.&amp;#160; There are several sets of types decorated with Serializable which are serializable and do not meet these rules. &lt;/p&gt;

&lt;p&gt;Take for instance types that violate rule 2.2.&amp;#160; By having a field whose type is not sealed, it is possible to construct a runtime instance which contains a value whose type is not serializable.&amp;#160; The following type fits into this category.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Serializable&lt;/span&gt;]
&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OnlyKnownPerInstance &lt;/span&gt;{
    &lt;span style="color: blue"&gt;private object &lt;/span&gt;m_field1;
}&lt;/pre&gt;

&lt;p&gt;Whether or not an instance of this type is serializable depends on the value of m_field1.&amp;#160; So the only way to prove it is serializable is to look at the runtime information.&amp;#160; This makes any definitive analysis on the type impossible.&amp;#160; The actual object must be inspected.&lt;/p&gt;

&lt;p&gt;The other case to examine are types implementing ISerializable.&amp;#160; Serialization is a custom task for instances of these types and is done in imperative code.&amp;#160; Proving these types are serializable involves actual algorithm inspection and is beyond the scope of this blog post.&amp;#160; But suffice to say, proving these are serializable is an order of magnitude more difficult. &lt;/p&gt;

&lt;p&gt;Getting back to the crux of this article.&amp;#160; What is the best way to determine if an object is serializable or not?&amp;#160; Bottom line, there is no good way.&amp;#160; The only 100% definitive way is to serialize the object and see if it succeeds or not.&amp;#160; This is problematic because it is not future proof.&amp;#160; It only tells you that the object &lt;strong&gt;was &lt;/strong&gt;serializable.&amp;#160; This is a very important distinction.&amp;#160; It’s possible for the object to be mutated in a different state later on which will prevent it from being properly serializable.&amp;#160; &lt;/p&gt;

&lt;p&gt;If serialization of a parameter is very important to the semantics of an API this is the only way to ensure the semantics are not violated is to serialize the object immediately and store the binary data.&amp;#160; Otherwise you can only make a loose guarantee that an attempt to serialize in the future will succeed.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9499985" 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/API+Design/default.aspx">API Design</category></item><item><title>Building a WeakReference Hashtable</title><link>http://blogs.msdn.com/jaredpar/archive/2009/03/03/building-a-weakreference-hashtable.aspx</link><pubDate>Tue, 03 Mar 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9389341</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9389341.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9389341</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9389341</wfw:comment><description>&lt;p&gt;Recently I ran into a situation on a personal project where I needed a hashtable like structure for a set of WeakReference values.&amp;#160; When poking around for an existing implementation I saw found several versions which were very thin, type safe wrapper around a Dictionary&amp;lt;TKey,WeakReference&amp;gt; (usually the class even implements IDictionary&amp;lt;TKey,TValue&amp;gt; directly).&amp;#160; While this produces a type safe API it fails to take into account the different nature of a WeakReference.&amp;#160; Because a WeakReference is constantly being collected without explicit user action it alters the types of operations that be performed on them.&amp;#160; Failing to take this into account produced APIs which lead users to write incorrect code.&lt;/p&gt;  &lt;p&gt;Finding no suitable implementation I set off to build my own.&amp;#160; It took several iterations and I thought the result and process would be fun to share the design experience as a blog post.&amp;#160; &lt;/p&gt;  &lt;p&gt;Let start with the basics.&amp;#160; At a high level the API should appear to the user as a type safe Dictionary&amp;lt;TKey,TValue&amp;gt;.&amp;#160; Under the hood all values will be stored in an instance of WeakReference in order to enable collection.&amp;#160; But this is an implementation detail and should not be visible to the user.&amp;#160;&amp;#160; The user should only see type safe keys and values.&lt;/p&gt;  &lt;p&gt;A standard Hashtable works on the concept of a key/value pair.&amp;#160; A value is associated with a particular key in the table and at any time, the value can be retrieved from the hashtable with the specified key.&amp;#160; A key can be determined to be valid simply by ascertaining it’s presence in the underlying table.&amp;#160; The value is irrelevant, it’s mere presence makes it valid. &lt;/p&gt;  &lt;p&gt;A weak hashtable will work on the same concept but have a much different implementation.&amp;#160; Keys are only valid if they point to an actual value.&amp;#160; Since the value in the hashtable is a WeakReference the mere presence of the key does not determine it’s validity.&amp;#160; Only the presence of the key and the value contained within the weak reference determines the validity of a key.&amp;#160; &lt;/p&gt;  &lt;p&gt;This seems like an obvious assumption but it has a dramatic impact on the type of API a weak hashtable can have.&amp;#160; Lets take a simple property such as Count for an example of why this is important.&amp;#160; Count on a hashtable is used to determine the number of valid key/value pairs in the table.&amp;#160; On a normal hashtable, this count is simply incremented and decremented with the corresponding Add and Remove API’s.&amp;#160; With a weak hashtable, any given run of the garbage collector can affect the count of key/value pairs by collecting a value.&amp;#160; This means a simple counter cannot be used to keep track of the valid key/value pairs.&amp;#160; &lt;/p&gt;  &lt;p&gt;In order to get the actual Count every singe value must be accessed an verified that it is still alive.&amp;#160; What’s even worse is that once a value is determined to exist, it must be stored for the duration of the Count method.&amp;#160; Otherwise a GC could occur in the middle of the loop and collect Values that were marked as still alive.&amp;#160; &lt;/p&gt;  &lt;p&gt;This is what Count would need to look like …&amp;#160; &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;WeakHashtable&lt;/span&gt;&amp;lt;TKey,TValue&amp;gt; {
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;TKey, &lt;span style="color: #2b91af"&gt;WeakReference&lt;/span&gt;&amp;gt; _map;
    &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;var &lt;/span&gt;list = _map.Values
                .Select(x =&amp;gt; x.Target)
                .Where(x =&amp;gt; x != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
                .ToList();
            &lt;span style="color: blue"&gt;return &lt;/span&gt;list.Count;
        }
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Count transformed from a simple O(1) return of an internal counter to a O(N) method which allocates memory.&amp;#160; Worse yet, the return value is practically useless.&amp;#160; As soon as the value is returned it cannot be considered to be valid.&amp;#160; A GC could kick in and invalidate half the table.&amp;#160; Count would in fact be giving the user information about the object in the past.&amp;#160; &lt;/p&gt;

&lt;p&gt;In some ways, this problem is similar to issues encountered with multi-threaded applications.&amp;#160; In between every line of your code there is another operation, in this case the GC, which can alter the state of your structure.&amp;#160; &lt;/p&gt;

&lt;p&gt;The only API’s that can ask questions about a value and still have a reasonable use by the user must return the value with the call.&amp;#160; Returning the value will, at least temporarily, provide a GC root and prevent the object from being collected.&amp;#160; It gives the user a chance to use the value before it’s taken out from under them. &lt;/p&gt;

&lt;p&gt;A good API comparison here are operations such as Contains and TryGetValue.&amp;#160; Contains holds no value to the user because as soon as the call returns the GC can collect the value.&amp;#160; TryGetValue on the other hand returns the value in question thus locking it in memory and preventing a collection.&amp;#160; &lt;/p&gt;

&lt;p&gt;When designing the API for a weak hashtable I tried to keep it simple and stick to these ideas.&amp;#160; I started with the &lt;a href="http://msdn.microsoft.com/en-us/library/s4ys34ea.aspx"&gt;IDictionary&amp;lt;TKey,TValue&amp;gt;&lt;/a&gt; interface and removed the methods which hold no value for the end user due to GC limitations.&amp;#160; In the end I was left with only the following.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;void Add(TKey key, TValue value) &lt;/li&gt;

  &lt;li&gt;bool Remove(TKey key) &lt;/li&gt;

  &lt;li&gt;void Clear() &lt;/li&gt;

  &lt;li&gt;bool TryGetValue(TKey key, out TValue value) &lt;/li&gt;

  &lt;li&gt;List&amp;lt;TValue&amp;gt; Values { get; } &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I also added the following methods&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;List&amp;lt;Tuple&amp;lt;TKey,TValue&amp;gt;&amp;gt; Pairs&amp;#160; { get; } &lt;/li&gt;

  &lt;li&gt;Put(TKey key, TValue value) &lt;/li&gt;

  &lt;li&gt;Option&amp;lt;TValue&amp;gt; TryGetValue(TKey key); &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Values property returns a List&amp;lt;TValue&amp;gt; implementation instead of IEnumerable&amp;lt;TValue&amp;gt;&amp;#160; In order to guarantee the values remain in existence they must be rooted in some structure.&amp;#160; The easy choice is a List&amp;lt;TValue&amp;gt;.&amp;#160; Since a List&amp;lt;TValue&amp;gt; must be created anyways, why return a less accessible interface such as IEnumerable&amp;lt;TValue&amp;gt;?&amp;#160; &lt;/p&gt;

&lt;p&gt;At first I did consider a design where Values returned IEnumerable.&amp;#160; It is fairly simple to implement with a C# iterator.&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;IEnumerable&lt;/span&gt;&amp;lt;TValue&amp;gt; Values {
    &lt;span style="color: blue"&gt;get &lt;/span&gt;{
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;weakRef &lt;span style="color: blue"&gt;in &lt;/span&gt;_map.Values) {
            &lt;span style="color: blue"&gt;var &lt;/span&gt;obj = weakRef.Target;
            &lt;span style="color: blue"&gt;if &lt;/span&gt;(obj != &lt;span style="color: blue"&gt;null&lt;/span&gt;) {
                &lt;span style="color: blue"&gt;yield return &lt;/span&gt;(TValue)obj;
            }
        }
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The problem though is that anything more than a simple .ForEach() over the IEnumerable may behave unexpectedly.&amp;#160; Consecutive calls to GetEnumerator can produce different enumerations with no explicit user alteration of the table.&amp;#160; I’ve seen several APIs which (rightly or wrongly) make this assumption.&amp;#160; Given the user is not explicitly modifying the collection, it is not a necessarily bad assumption to make.&amp;#160; However it would not work for a collection of this type.&lt;/p&gt;

&lt;p&gt;I intentionally left off Keys here.&amp;#160; Keys are only valid when they have a live value in the table.&amp;#160; Unless the Value is returned with Key this cannot be guaranteed.&amp;#160; The Pairs property serves this role.&amp;#160; &lt;/p&gt;

&lt;p&gt;This post went a bit longer than I originally intended.&amp;#160; I also wanted to discuss how compaction of the table should work in a weak hashtable.&amp;#160; I’ll save that for next time.&amp;#160; &lt;/p&gt;

&lt;p&gt;Here is the implementation of the dictionary without any compaction support.&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;WeakDictionary&lt;/span&gt;&amp;lt;TKey, TValue&amp;gt; {
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;TKey, &lt;span style="color: #2b91af"&gt;WeakReference&lt;/span&gt;&amp;gt; m_map;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;&amp;lt;TKey, TValue&amp;gt;&amp;gt; Pairs {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{
            &lt;span style="color: blue"&gt;return &lt;/span&gt;m_map
                    .Select(p =&amp;gt; &lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;.Create(p.Key, p.Value.Target))
                    .Where(t =&amp;gt; t.Second != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
                    .Select(t =&amp;gt; &lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;.Create(t.First, (TValue)t.Second))
                    .ToList();
        }
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;TValue&amp;gt; Values {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;Pairs.Select(x =&amp;gt; x.Second).ToList(); }
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;WeakDictionary()
        : &lt;span style="color: blue"&gt;this&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;EqualityComparer&lt;/span&gt;&amp;lt;TKey&amp;gt;.Default) {
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;WeakDictionary(&lt;span style="color: #2b91af"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;TKey&amp;gt; comparer) {
        m_map = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;TKey, &lt;span style="color: #2b91af"&gt;WeakReference&lt;/span&gt;&amp;gt;(comparer);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Add(TKey key, TValue value) {
        m_map.Add(key, &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WeakReference&lt;/span&gt;(value));
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Put(TKey key, TValue value) {
        m_map[key] = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WeakReference&lt;/span&gt;(value);
    }

    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;Remove(TKey key) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;m_map.Remove(key);
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;TValue&amp;gt; TryGetValue(TKey key) {
        &lt;span style="color: #2b91af"&gt;WeakReference &lt;/span&gt;weakRef;
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(!m_map.TryGetValue(key, &lt;span style="color: blue"&gt;out &lt;/span&gt;weakRef)) {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;.Empty;
        }

        &lt;span style="color: blue"&gt;var &lt;/span&gt;target = weakRef.Target;
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(target == &lt;span style="color: blue"&gt;null&lt;/span&gt;) {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;.Empty;
        }

        &lt;span style="color: blue"&gt;return &lt;/span&gt;(TValue)target;
    }

    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;TryGetValue(TKey key, &lt;span style="color: blue"&gt;out &lt;/span&gt;TValue value) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;option = TryGetValue(key);
        value = option.ValueOrDefault;
        &lt;span style="color: blue"&gt;return &lt;/span&gt;option.HasValue;
    }
}&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=9389341" 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/API+Design/default.aspx">API Design</category></item><item><title>A more usable API for a mutable thread safe collection</title><link>http://blogs.msdn.com/jaredpar/archive/2009/02/16/a-more-usable-thread-safe-collection.aspx</link><pubDate>Mon, 16 Feb 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9424930</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>17</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9424930.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9424930</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9424930</wfw:comment><description>
&lt;p&gt;In my last &lt;a href="http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx" mce_href="http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx"&gt;post&lt;/a&gt; we discussed the problems with designing a safer API for mutable thread safe collections that employ only an internal locking system.&amp;nbsp; The result was an API that was more difficult to mess up, yet pretty much unusable.&amp;nbsp; Lets take a look at this problem and see if we can come up with a usable API that still helps to eliminate mistakes.&amp;nbsp; &lt;/p&gt;
  
&lt;p&gt;One of the main issues I have with mutable thread safe collections is the use of decision procedures such as Count and Contains.&amp;nbsp; Procedures such these only return information that pertains to the collection as it existed at a previous point in time.&amp;nbsp; It can provide no relevant information to the collection in it’s current state and only encourages the user to write bad code.&amp;nbsp; For example.&amp;nbsp; &lt;/p&gt;
  
&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;if &lt;/span&gt;(col.Count &amp;gt; 0) {&lt;br&gt;    &lt;span style="color: green;"&gt;// Collection can be modified before this next line executes leading to &lt;br&gt;    // an error condition&lt;br&gt;    &lt;/span&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;first = col[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;Therefore they have no place on a mutable thread safe collection.&amp;nbsp; Yet, once you take away these procedures, you’re left with a collection that is virtually useless.&amp;nbsp; It can only have a minimal API by which to access data.&amp;nbsp; Here is the last example we were left with &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;public void &lt;/span&gt;Add(T value) { ... }&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;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;/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 is hardly a usable API.&amp;nbsp; What’s worse, as wekempf point out, is that I inadvertently exposed a decision procedure in this API.&amp;nbsp; It’s possible to infer state about a lower or equal index by a successful return result from TryGet().&amp;nbsp; For example, a user may say that “if I can access element 2, then surely element 1 must exist”.&amp;nbsp; The result would still be evident in code (ignoring the return value of a TryGet method should be a red flag).&amp;nbsp; But a better choice for this method would have been a TryGetFirst().&amp;nbsp; &lt;/p&gt;

&lt;p&gt;At the end of the day, users are going to want some level of determinism out of their collections.&amp;nbsp; It’s possible to program against API’s like the above, but most people won’t do it.&amp;nbsp; In order to be more used, the collection must be able to reliably implement procedures such as Count and Contains and allow the user to use the return to reason about the state of the collection.&lt;/p&gt;

&lt;p&gt;One way to do this is to simply exposed the internal lock to the consumer of the collection.&amp;nbsp; Consumers can take the lock and then query to their hearts content.&amp;nbsp; Lets do a quick modification of the original sample to allow for this.&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;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 object &lt;/span&gt;SyncLock { &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_lock; } }&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;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now we can go back to the original sample code and write a version which can use the decision procedures safely.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;lock &lt;/span&gt;(col.SyncLock) {&lt;br&gt;    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(col.Count &amp;gt; 0) {&lt;br&gt;        &lt;span style="color: blue;"&gt;var &lt;/span&gt;first = col[0];&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;This code will function correctly.&amp;nbsp; But the API leaves a lot to be desired.&amp;nbsp; In particular … &lt;/p&gt;

&lt;ol&gt;
  
&lt;li&gt;It provides no guidance to the user as to which procedures must be accessed with the SyncLock object locked.&amp;nbsp; They can just as easily write the original bad sample code.&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;
    
&lt;p&gt;All procedures used within the lock reacquire the lock recursively which is definitely &lt;a href="http://zaval.org/resources/library/butenhof1.html" mce_href="http://zaval.org/resources/library/butenhof1.html"&gt;not advisable&lt;/a&gt;.&amp;nbsp; We could provide properties which do not acquire the lock such as CountNoLock that work around this problem. While ok in small doses, it's just a matter of time before you see this snippet in the middle of a huge mostly undocumented function&lt;/p&gt;

    
&lt;pre class="code"&gt;&lt;span style="color: green;"&gt;// Lock should be held at this point&lt;br&gt;&lt;/span&gt;&lt;span style="color: blue;"&gt;int &lt;/span&gt;count = col.CountNoLock;&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 makes my eyes bleed&lt;/p&gt;
  &lt;/li&gt;

  
&lt;li&gt;The API provides 0 information to the user on exactly what the rules are for this lock.&amp;nbsp; It would be left as an artifact in documentation (which you simply cannot count on users reading).&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;There is really nothing telling the user that they ever have to unlock the collection.&amp;nbsp; Surely, any user entering into the world of threading should know this but if they do a Monitor.Enter call without a corresponding Monitor.Exit, they will receive no indication this is a bad idea.&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;Overall this collection requires a lot of new knowledge about the collection to use &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This design though is exactly how a “synchronized” collection in 1.0 version of the BCL worked.&amp;nbsp; This code is essentially what you would get by passing an ArrayList instance to ArrayList.Synchronized (and most other BCL 1.0 collections).&amp;nbsp;&amp;nbsp; It was problematic enough that all of the new collections in 2.0 did not implement this &lt;i&gt;feature&lt;/i&gt;.&amp;nbsp; Here’s the BCL team’s explanation on this &lt;a href="http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx" title="http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx" mce_href="http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx"&gt;http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Overall this design poses several problems because it exposes internal implementation details directly to the consumer.&amp;nbsp; An improved design should seek to hide the lock from direct access.&amp;nbsp; What we really want is a way to not even provide API’s like Count and Contains unless the object is already in a locked state.&amp;nbsp; This prevents them from being used at all in an incorrect scenario.&lt;/p&gt;

&lt;p&gt;Lets run with this idea to design a more usable thread safe queue.&amp;nbsp; First we’ll divide the interface for a queue into two parts.&amp;nbsp; &lt;/p&gt;

&lt;ol&gt;
  
&lt;li&gt;All procedures that have 0 reliance on the internal state of the collection.&amp;nbsp; Namely Enqueue, and Clear.&amp;nbsp; No state is required to use these methods &lt;/li&gt;

  
&lt;li&gt;All procedures that rely on the internal state of the collection to function correctly.&amp;nbsp; &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The ThreadSafeQueue class will contain all of the methods in category #1.&amp;nbsp; It will also provide a method which returns an instance of an interface which has all of the methods in category #2.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public interface &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ILockedQueue&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: rgb(43, 145, 175);"&gt;IDisposable&lt;/span&gt;{&lt;br&gt;    &lt;span style="color: blue;"&gt;int &lt;/span&gt;Count { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; }&lt;br&gt;    &lt;span style="color: blue;"&gt;bool &lt;/span&gt;Contains(T value);&lt;br&gt;    T Dequeue();&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;The implementation of this interface object will acquire the internal lock of the original ThreadSafeQueue during construction and hold it for the duration if it’s lifetime.&amp;nbsp; This effectively freezes the queue allowing for decision procedures to be used reliably.&amp;nbsp; Implementing IDisposable and releasing the lock in the Dispose method provides a measure of lifetime management.&amp;nbsp;&amp;nbsp; &lt;/p&gt;

&lt;p&gt;The rest of the code sample is below.&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;ThreadSafeQueue&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;#region &lt;/span&gt;LockedQueue&lt;br&gt;    &lt;span style="color: blue;"&gt;private sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;LockedQueue &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;ILockedQueue&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;ThreadSafeQueue&lt;/span&gt;&amp;lt;T&amp;gt; m_outer;&lt;br&gt;        &lt;span style="color: blue;"&gt;internal &lt;/span&gt;LockedQueue(&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeQueue&lt;/span&gt;&amp;lt;T&amp;gt; outer) {&lt;br&gt;            m_outer = outer;&lt;br&gt;            &lt;span style="color: rgb(43, 145, 175);"&gt;Monitor&lt;/span&gt;.Enter(m_outer.m_lock);&lt;br&gt;        }&lt;br&gt;&lt;br&gt;        &lt;span style="color: blue;"&gt;#region &lt;/span&gt;ILockedQueue&amp;lt;T&amp;gt; Members&lt;br&gt;        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Count { &lt;br&gt;            &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_outer.m_queue.Count; }&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;return &lt;/span&gt;m_outer.m_queue.Contains(value);&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;public &lt;/span&gt;T Dequeue() {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_outer.m_queue.Dequeue();&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;#endregion&lt;br&gt;        #region &lt;/span&gt;IDisposable Members&lt;br&gt;        &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Dispose() {&lt;br&gt;            Dispose(&lt;span style="color: blue;"&gt;true&lt;/span&gt;);&lt;br&gt;            &lt;span style="color: rgb(43, 145, 175);"&gt;GC&lt;/span&gt;.SuppressFinalize(&lt;span style="color: blue;"&gt;this&lt;/span&gt;);&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;private void &lt;/span&gt;Dispose(&lt;span style="color: blue;"&gt;bool &lt;/span&gt;disposing) {&lt;br&gt;            &lt;span style="color: rgb(43, 145, 175);"&gt;Debug&lt;/span&gt;.Assert(disposing, &lt;span style="color: rgb(163, 21, 21);"&gt;"ILockedQueue implementations must be explicitly disposed"&lt;/span&gt;); &lt;br&gt;            &lt;span style="color: blue;"&gt;if &lt;/span&gt;(disposing) {&lt;br&gt;                &lt;span style="color: rgb(43, 145, 175);"&gt;Monitor&lt;/span&gt;.Exit(m_outer.m_lock);&lt;br&gt;            }&lt;br&gt;        }&lt;br&gt;        ~LockedQueue() {&lt;br&gt;            Dispose(&lt;span style="color: blue;"&gt;false&lt;/span&gt;);&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;#endregion&lt;br&gt;    &lt;/span&gt;}&lt;br&gt;    &lt;span style="color: blue;"&gt;#endregion&lt;br&gt;&lt;br&gt;    private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Queue&lt;/span&gt;&amp;lt;T&amp;gt; m_queue = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Queue&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 &lt;/span&gt;ThreadSafeQueue() { }&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Enqueue(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_queue.Enqueue(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Clear() {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_queue.Clear();&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ILockedQueue&lt;/span&gt;&amp;lt;T&amp;gt; Lock() {&lt;br&gt;        &lt;span style="color: blue;"&gt;return new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;LockedQueue&lt;/span&gt;(&lt;span style="color: blue;"&gt;this&lt;/span&gt;);&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;

&lt;p&gt;This design now cleanly separates out the two modes by which the collection can be asked.&amp;nbsp; It completely hides the explicit synchronization aspects from the users and replaces it with design patterns (such as IDisposable) that they are likely already familiar with.&amp;nbsp; Now our original bad sample can be rewritten as follows.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;static void &lt;/span&gt;Example1(&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeQueue&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt; queue) {&lt;br&gt;    &lt;span style="color: blue;"&gt;using &lt;/span&gt;(&lt;span style="color: blue;"&gt;var &lt;/span&gt;locked = queue.Lock()) {&lt;br&gt;        &lt;span style="color: blue;"&gt;if &lt;/span&gt;(locked.Count &amp;gt; 0) {&lt;br&gt;            &lt;span style="color: blue;"&gt;var &lt;/span&gt;first = locked.Dequeue();&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;No explicit synchronization code is needed by the user.&amp;nbsp; This design makes it much harder for the user to make incorrect assumptions or misuses of the collection.&amp;nbsp; The “decision procedures” are simply not available unless the collection is in a locked state.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;As with most thread safe designs, there are ways in which this code can be used incorrectly &lt;/p&gt;

&lt;ol&gt;
  
&lt;li&gt;
    
&lt;p&gt;Using an instance of ILockedQueue&amp;lt;T&amp;gt; after it’s been disposed.&amp;nbsp; This though is already considered taboo though and we can rely on existing user knowledge to help alleviate this problem.&amp;nbsp; Additionally, static analysis tools, such as FxCop, will flag this as an error.&lt;/p&gt;

    
&lt;p&gt;&amp;nbsp;&lt;/p&gt;

    
&lt;p&gt;With a bit more rigor this can also be prevented. Simply add a disposed flag and check it on entry into every method.&lt;/p&gt;
  &lt;/li&gt;

  
&lt;li&gt;It’s possible for the user to maintain values, such as Count, between calls to Lock and use it to make an incorrect assumption about the state of the list.&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;If the user fails to dispose the ILockedQueue&amp;lt;T&amp;gt; instance it will be forever locked.&amp;nbsp; Luckily FxCop will also flag this as an error since it’s an IDisposable.&amp;nbsp; It’s not a foolproof mechanism though. &lt;/li&gt;

  
&lt;li&gt;There is nothing that explicitly says to the user “please only use ILockedQueue&amp;lt;T&amp;gt; for a very short time”.&amp;nbsp; IDisposable conveys this message to a point but it’s certainly not perfect.&lt;/li&gt;

  
&lt;li&gt;The actual ILockedQueue&amp;lt;T&amp;gt; implementation is not thread safe.&amp;nbsp; Ideally users won’t pass instances of IDisposable between threads but it is something to think about.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The good news is that two of these flaws (1 and 3) are issues with existing types and tools are already designed to weed them out.&amp;nbsp; FxCop will catch common cases for both of them.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;Also, many of these cases are considered bad code in the absence of a thread safe collection.&amp;nbsp; This allows users to rely on existing knowledge instead of forcing them to learn new design patterns for mutable thread safe collections.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;Overall I feel like this design is a real win over the other versions.&amp;nbsp; It provides an API which helps to limit the mistakes a user can make with a mutable thread safe collection without requiring a huge deal of new patterns in order to use.&amp;nbsp; &lt;/p&gt;
&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9424930" 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/API+Design/default.aspx">API Design</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>BclExtras Library</title><link>http://blogs.msdn.com/jaredpar/archive/2009/01/23/bclextras-library.aspx</link><pubDate>Fri, 23 Jan 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9372192</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9372192.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9372192</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9372192</wfw:comment><description>&lt;p&gt;I published a .Net utility library on &lt;a href="http://code.msdn.microsoft.com"&gt;Code Gallery&lt;/a&gt; today called &lt;a href="http://code.msdn.microsoft.com/BclExtras"&gt;BclExtras&lt;/a&gt;.&amp;#160; It’s a set of classes meant to be used in addition to the standard .Net base class libraries (BCL).&amp;#160; The main focuses of the library are functional programming, multi-threading, LINQ extensions, unit testing and API’s designed to support type inference.&lt;/p&gt;  &lt;p&gt;This project evolved from various classes and constructs I was using in personal projects.&amp;#160; For the last year or so I’ve kept as a separate tested library.&amp;#160; It started out with a lot of multi-threaded code constructs but lately is leaning to a lot of functional style API’s and collections.&amp;#160; &lt;/p&gt;  &lt;p&gt;The library includes source and binaries for .Net 2.0 and .Net 3.5.&amp;#160; The .Net 2.0 version of the library includes many constructs added in 3.5 that don’t rely on any 2.0SP1 CLR features.&amp;#160; Examples are Func&amp;lt;T&amp;gt;, Action&amp;lt;T&amp;gt;, the Extension attribute and a subset of the LINQ Enumerable class.&amp;#160; It allows for most LINQ expressions in a 2.0 targeted application. These types are removed in the 3.5 version to avoid conflicts with types in System.Core.&amp;#160; &lt;/p&gt;  &lt;p&gt;I’ve previously released this library under the name &lt;a href="http://code.msdn.microsoft.com/RantPack"&gt;RantPack&lt;/a&gt;.&amp;#160; It originally started out as personal utility library of mine and hence ended up with the somewhat obscure name.&amp;#160; But, besides to me, RantPack doesn’t really convey a useful meaning.&amp;#160; So I decided to give it a more meaningful name for the general population.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9372192" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/DotNet/default.aspx">DotNet</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/RantPack/default.aspx">RantPack</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/BclExtras/default.aspx">BclExtras</category></item><item><title>If you implement IEquatable&lt;T&gt; you still must override Object’s Equals and GetHashCode</title><link>http://blogs.msdn.com/jaredpar/archive/2009/01/15/if-you-implement-iequatable-t-you-still-must-override-object-s-equals-and-gethashcode.aspx</link><pubDate>Thu, 15 Jan 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9306048</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9306048.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9306048</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9306048</wfw:comment><description>&lt;p&gt;CLR 2.0 introduced &lt;a href="http://msdn.microsoft.com/en-us/library/ms131187.aspx"&gt;IEquatable&amp;lt;T&amp;gt;&lt;/a&gt; which is an interface that allows for type safe equality comparisons.&amp;#160; Previously, the best available method for comparing equality was the virtual &lt;a href="http://msdn.microsoft.com/en-us/library/system.object.equals.aspx"&gt;Object Equals&lt;/a&gt; method.&amp;#160; The method is loosely typed since it takes an object as a parameter.&amp;#160; This is easy enough to deal with on the client with a simple cast to the appropriate type.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Student &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public override bool &lt;/span&gt;Equals(&lt;span style="color: blue"&gt;object &lt;/span&gt;obj) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;other = obj &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Student&lt;/span&gt;;
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(other == &lt;span style="color: blue"&gt;null&lt;/span&gt;) {
            &lt;span style="color: blue"&gt;return false&lt;/span&gt;;
        }
        &lt;span style="color: green"&gt;// rest of comparison
    &lt;/span&gt;}
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;IEquatable&amp;lt;T&amp;gt; is a significant improvement over this pattern because it provides a strongly typed equals method.&amp;#160; This protects both the caller and callee from passing incompatible object types.&amp;#160; Additionally it avoids the overhead of boxing for value types.&lt;/p&gt;

&lt;p&gt;These benefits are nice but if you implement IEquatable&amp;lt;T&amp;gt; you still must override Equals(object) and GetHashCode.&amp;#160; Not doing so is wrong and &lt;strong&gt;will&lt;/strong&gt; cause you pain down the road.&amp;#160; I’ve explored this &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/05/09/iequatable-of-t-and-gethashcode.aspx"&gt;topic&lt;/a&gt; briefly in the past but wanted to expand on it a bit with some concrete examples. &lt;/p&gt;

&lt;p&gt;Before we get into the technical details of why, lets look at this from an expectation point of view.&amp;#160; Implementing IEquatable&amp;lt;T&amp;gt; is a statement that “this object knows what it means to be equal.”&amp;#160; This in effect adds a contract to your class declaring that it knows how to be compared for equality.&amp;#160; Your object should live up to these expectations in order to avoid confusing other programmers who aren’t intimately familiar with your class.&amp;#160; Confusing programmers is rarely a good idea.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Issue #1: IEqualityComparer&amp;lt;T&amp;gt; requires GetHashCode()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Strongly typed collections such as Dictionary&amp;lt;TKey,TValue&amp;gt; and HashSet&amp;lt;T&amp;gt; must be able to compare objects for equality in order to function.&amp;#160; Starting in 2.0, the BCL provides an interface by which object equality semantics can be performed: IEqualityComparer&amp;lt;T&amp;gt;.&amp;#160; This class is used in many other places besides collections, but inspecting the collection classes is the easiest way to get a feel for it’s use.&lt;/p&gt;

&lt;p&gt;Lets take a look at the definition of IEqualityComparer&amp;lt;T&amp;gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; {
    &lt;span style="color: blue"&gt;bool &lt;/span&gt;Equals(T x, T y);
    &lt;span style="color: blue"&gt;int &lt;/span&gt;GetHashCode(T obj);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The default definition is an internal class in the BCL named GenericEqualityComparer&amp;lt;T&amp;gt;. The default implementation of IEqualityComparer&amp;lt;T&amp;gt; relies on IEquatable&amp;lt;T&amp;gt; for it’s implementation.&amp;#160; &lt;/p&gt;

&lt;p&gt;But if it uses IEquatable&amp;lt;T&amp;gt; for it’s implementation how can it possible implement GetHashCode()?&amp;#160; Simple, it uses Object.GetHashCode().&amp;#160; This means an object must implement IEquatable&amp;lt;T&amp;gt; and GetHashCode() in order to function correctly in places where IEqualityComparer&amp;lt;T&amp;gt; is used.&lt;/p&gt;

&lt;p&gt;But wait, I don’t actually implement IEqualityComparer&amp;lt;T&amp;gt; anywhere so I’m safe right?&amp;#160; Unfortunately no.&amp;#160; Very few people actually implement IEqualityComparer&amp;lt;T&amp;gt;.&amp;#160; Instead they use EqualityComparere&amp;lt;T&amp;gt;.Default to access a given IEqualityComparer&amp;lt;T&amp;gt; for a given type T.&amp;#160; &lt;/p&gt;

&lt;p&gt;In fact, the standard pattern for methods which take an IEqualityComparer&amp;lt;T&amp;gt; is to have an overload that doesn’t and pass EqualityComparer&amp;lt;T&amp;gt;.Default to the one that does.&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;Example &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; Distinct&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;Distinct(source, &lt;span style="color: #2b91af"&gt;EqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt;.Default);
    }
    &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; Distinct&amp;lt;T&amp;gt;(
        &lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, 
        &lt;span style="color: #2b91af"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; comparer) {
        &lt;span style="color: green"&gt;// implementation
    &lt;/span&gt;}
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;If your object implements IEquatable&amp;lt;T&amp;gt; this will eventually cause it to create an instance of GenericEqualityComparer&amp;lt;T&amp;gt; and hence a reliance on GetHashCode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Issue #2: Non-Strongly typed collections and Frameworks don’t use IEquatable&amp;lt;T&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;IEquatable&amp;lt;T&amp;gt; only provides equality comparisons in strongly typed scenarios.&amp;#160; It is not convenient to access this interface in less strongly typed scenarios.&amp;#160; Consider for instance the original 1.0 collection classes: ArrayList, Hashtable, etc …&amp;#160; These are all object based collections and have no way in which to cast to IEquatable&amp;lt;T&amp;gt;.&amp;#160; Instead these collections must rely on the Object based methods of Equality.&amp;#160; &lt;/p&gt;

&lt;p&gt;Without implementing Object.Equals and Object.GetHashCode your type will not actually do any sort of comparison.&amp;#160; This will cause lots of incorrect behavior for programmers who expect the class to understand equality.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Person &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IEquatable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&amp;gt; {
    &lt;span style="color: blue"&gt;public readonly string &lt;/span&gt;Name;
    &lt;span style="color: blue"&gt;public &lt;/span&gt;Person(&lt;span style="color: blue"&gt;string &lt;/span&gt;name) {
        Name = name;
    }
    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;Equals(&lt;span style="color: #2b91af"&gt;Person &lt;/span&gt;other) {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(other == &lt;span style="color: blue"&gt;null&lt;/span&gt;) {
            &lt;span style="color: blue"&gt;return false&lt;/span&gt;;
        }
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StringComparer&lt;/span&gt;.Ordinal.Equals(Name, other.Name);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;EqualityCheck() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;p = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Bob&amp;quot;&lt;/span&gt;);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;list = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArrayList&lt;/span&gt;();
    list.Add(p);
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(list.Contains(p)); &lt;span style="color: green"&gt;// Prints: True
    &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(list.Contains(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Bob&amp;quot;&lt;/span&gt;)));    &lt;span style="color: green"&gt;// Prints: False
&lt;/span&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This goes against expectation.&amp;#160; Both Person instances in this case are equal by definition of Person yet Contains fails.&amp;#160; Implementing Object.Equals and Object.GetHashCode will remove this confusion.&lt;/p&gt;

&lt;p&gt;The list of frameworks which still use loosely typed collections include WinForms, WPF, WebForms, etc …&amp;#160; It’s almost inevitable that you will end up using a loosely typed collection in your project somewhere.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Isssue #3: Equality and hash codes are linked in the BCL&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Rightly or wrongly, equality and hash codes are unbreakably linked in the BCL.&amp;#160; If an object can be compared for equality it also must be able to produce a hashcode.&amp;#160;&amp;#160; This implicit contract exists many places throughout the framework.&amp;#160; &lt;/p&gt;

&lt;p&gt;As previously displayed, implementing Object.Equals() after implementing IEquatable&amp;lt;T&amp;gt; is straight forward and boiler plate code.&amp;#160; Object.GetHashCode can be a bit trickier because there are many &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/04/28/properly-implementing-equality-in-vb.aspx"&gt;implicit contracts&lt;/a&gt; for GetHashCode.&amp;#160; Often mutable objects cannot provide an efficient hashing mechanism.&amp;#160; In that case just &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/06/03/making-equality-easier.aspx"&gt;return 1&lt;/a&gt;.&amp;#160; This will satisfy all of the implicit contracts around GetHashCode() and takes little time to do.&amp;#160; Yes, it will cause a Dictionary to effectively be a linked list.&amp;#160; But that’s a heck of a lot better than simply not working at all.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9306048" 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/Patterns/default.aspx">Patterns</category></item><item><title>NotImplementedException vs. NotSupportedException</title><link>http://blogs.msdn.com/jaredpar/archive/2008/12/12/notimplementedexception-vs-notsupportedexception.aspx</link><pubDate>Fri, 12 Dec 2008 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9198047</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9198047.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9198047</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9198047</wfw:comment><description>&lt;p&gt;In responding to a recent &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/12/10/immutable-collections-and-backwards-compatibility.aspx"&gt;blog post&lt;/a&gt;, one of the readers, Jeremy Gray, noted that I was using a &lt;a href="http://msdn.microsoft.com/en-us/library/system.notimplementedexception.aspx"&gt;NotImplementedException&lt;/a&gt; where I should have been using a &lt;a href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx"&gt;NotSupportedException&lt;/a&gt;.&amp;#160; At first I did not agree.&amp;#160; There was a method on an interface which my underlying object could not implement therefore I felt the choice of &lt;a href="http://msdn.microsoft.com/en-us/library/system.notimplementedexception.aspx"&gt;NotImplementedException&lt;/a&gt; was an appropriate.&lt;/p&gt;  &lt;p&gt;However I was also not very familiar with &lt;a href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx"&gt;NotSupportedException&lt;/a&gt; and decided to investigate a bit more.&amp;#160; After all, part of the fun of blogging is being wrong in a very public fashion and this was certainly a golden opportunity.&amp;#160; The post was commenting on API design, what better way to be wrong than with a different API design issue?&lt;/p&gt;  &lt;p&gt;After doing a bit of research I agree with Jeremy and draw the following distinction between the two exception types&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;     &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx"&gt;NotSupportedException&lt;/a&gt;: Throw this exception when a type does not implement a method for which there is a corresponding property indicating whether or not the method in question is supported. &lt;/p&gt;      &lt;p&gt;For Example:&lt;/p&gt;      &lt;ul&gt;       &lt;li&gt;IColletion&amp;lt;T&amp;gt;.Add -&amp;gt; IsReadOnly &lt;/li&gt;        &lt;li&gt;Stream.Seek -&amp;gt; CanSeek &lt;/li&gt;        &lt;li&gt;Stream.Write -&amp;gt; CanWrite &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.notimplementedexception.aspx"&gt;NotImplementedException&lt;/a&gt;: Throw this exception when a type does not implement a method for any other reason. &lt;/p&gt;      &lt;p&gt;For Example: ICollection.Count, ICloneable.Clone, etc ... [1]&lt;/p&gt;   &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The method in question on my previous blog post was ICollection&amp;lt;T&amp;gt;.Add().&amp;#160; I was dealing with an immutable collection for which Add is not possible.&amp;#160; Since there is a property, IsReadOnly, which serves as an indicator that Add() is not allowed, &lt;a href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx"&gt;NotSupportedException&lt;/a&gt; is the better choice.&amp;#160; &lt;/p&gt;  &lt;p&gt;[1] Not implementing these methods is likely a bad idea.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9198047" 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/API+Design/default.aspx">API Design</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Exceptions/default.aspx">Exceptions</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>Comparing Continuations in C# and F# Part 3: Double wrong</title><link>http://blogs.msdn.com/jaredpar/archive/2008/11/13/comparing-continuations-in-c-and-f-part-3-double-wrong.aspx</link><pubDate>Thu, 13 Nov 2008 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9064743</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9064743.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9064743</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9064743</wfw:comment><description>&lt;p&gt;Is it better to be wrong once or to be right then think you’re wrong but find out you were right but wrong about being wrong? Besides the obvious be right the first time, it’s certainly an educational experience.&amp;#160; &lt;/p&gt;  &lt;p&gt;Here’s the original sample:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;FoldRight combine (sequence:seq&amp;lt;'a&amp;gt;) acc = 
    &lt;span style="color: blue"&gt;use &lt;/span&gt;e = sequence.GetEnumerator()
    &lt;span style="color: blue"&gt;let rec &lt;/span&gt;inner cont = 
        &lt;span style="color: blue"&gt;match &lt;/span&gt;e.MoveNext() &lt;span style="color: blue"&gt;with
            &lt;/span&gt;| &lt;span style="color: blue"&gt;true -&amp;gt; 
                let &lt;/span&gt;cur = e.Current
                inner (&lt;span style="color: blue"&gt;fun &lt;/span&gt;racc &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;cont (combine cur racc))
            | &lt;span style="color: blue"&gt;false -&amp;gt; &lt;/span&gt;cont acc
    inner (&lt;span style="color: blue"&gt;fun &lt;/span&gt;x &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;x )&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;a href="http://lorgonblog.spaces.live.com/blog/"&gt;Brian McNamara&lt;/a&gt; pointed out I wasn’t considering all of the call sites for this sample.&amp;#160; In addition to the recursive call to “inner” and the initial inner call, there is the actual recursive invocation of the of the continuations.&amp;#160; Effectively the “inner” function is building up a list of list of lambdas which call the combine function.&amp;#160; The output of the combine function is simply passed into the next lambda in the list.&amp;#160; The last lambda in the list is the identity lambda and returns the final call to combine.&amp;#160; This value is the actual value returned from the initial invocation “cont acc”.&amp;#160; Lambdas are methods under the hood.&amp;#160; Without a tail instruction, this chain of lambda calls will just as easily overflow the stack.&lt;/p&gt;

&lt;p&gt;Digging deeper into the compiled F# code we can view this call and indeed it is done with tail recursion.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt; 
.method public virtual instance !V Invoke(!U racc) cil managed
{
    .maxstack 8
    L_0000: nop 
    L_0001: ldarg.0 
    L_0002: ldfld class [FSharp.Core]Microsoft.FSharp.Core.FastFunc`2&lt;!0, !1&gt; Program/clo@9&lt;!U, !V, !A&gt;::cont
    L_0007: ldarg.0 
    L_0008: ldfld class [FSharp.Core]Microsoft.FSharp.Core.FastFunc`2&lt;!2, class [FSharp.Core]Microsoft.FSharp.Core.FastFunc`2&lt;!0, !0&gt;&amp;gt; Program/clo@9&lt;!U, !V, !A&gt;::combine
    L_000d: ldarg.0 
    L_000e: ldfld !2 Program/clo@9&lt;!U, !V, !A&gt;::cur
    L_0013: ldarg.1 
    L_0014: call !!0 [FSharp.Core]Microsoft.FSharp.Core.FastFunc`2&lt;!A, !U&gt;::InvokeFast2&lt;!U&gt;(class [FSharp.Core]Microsoft.FSharp.Core.FastFunc`2&lt;!0, class [FSharp.Core]Microsoft.FSharp.Core.FastFunc`2&lt;!1, !!0&gt;&amp;gt;, !0, !1)
    L_0019: tail 
    L_001b: callvirt instance !1 [FSharp.Core]Microsoft.FSharp.Core.FastFunc`2&lt;!U, !V&gt;::Invoke(!0)
    L_0020: ret 
}&lt;/pre&gt;

&lt;p&gt;The below code more accurately resembles the equivalent C# code that is generated for the above F# sample&amp;#160; (thanks Brian!).&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;TAcc Inner&amp;lt;TSource, TAcc&amp;gt;(
    &lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerator&lt;/span&gt;&amp;lt;TSource&amp;gt; e,
    &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TAcc, TSource, TAcc&amp;gt; combine,
    TAcc start,
    &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TAcc, TAcc&amp;gt; cont)
{
    &lt;span style="color: blue"&gt;while &lt;/span&gt;(e.MoveNext())
    {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;cur = e.Current;
        &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TAcc, TAcc&amp;gt; innerCont = cont;
        cont = (x) =&amp;gt; &lt;span style="color: green"&gt;/*need .tail here */&lt;/span&gt;innerCont(combine(x, cur));
    }
    &lt;span style="color: blue"&gt;return &lt;/span&gt;cont(start);
}

&lt;span style="color: blue"&gt;public static &lt;/span&gt;TAcc FoldRight&amp;lt;TSource, TAcc&amp;gt;(
    &lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; enumerable,
    &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TAcc, TSource, TAcc&amp;gt; combine,
    TAcc start)
{
    &lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;e = enumerable.GetEnumerator())
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;Inner(e, combine, start, (x) =&amp;gt; x);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;strong&gt;Previous Entries&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/11/10/comparing-continuations-in-f-and-c.aspx"&gt;Part 1&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/11/11/comparing-continuations-in-c-and-f-part-2.aspx"&gt;Part 2&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9064743" 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/F_2300_/default.aspx">F#</category></item></channel></rss>