<?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 : API Design</title><link>http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx</link><description>Tags: API Design</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><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>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>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>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>Custom Exceptions: When should you create them?</title><link>http://blogs.msdn.com/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx</link><pubDate>Mon, 20 Oct 2008 15:00:27 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8997282</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8997282.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8997282</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8997282</wfw:comment><description>&lt;p&gt;I think the best answer is: rarely.&amp;#160;&amp;#160; It's really hard to go straight to a justification here though.&amp;#160; I find that answering a different question will eventually shed led on when to create a new exception. &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&amp;quot;What are the benefits of creating a new/custom exception?&amp;quot;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The answers I come up with or have heard before are ...&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Provides a type safe mechanism for a developer to detect an error condition.&amp;#160; &lt;p&gt;Without a custom exception a developer would be forced to compare an existing value on an existing exception class in order to determine if a particular error occurred.&amp;#160; To ensure this was unique across applications and environments a unique identifier would need to be inserted as well (likely a GUID).&amp;#160; The resulting code would be quite ugly and maintainability would be a question mark.&amp;#160; &lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;Add situation specific data to an exception      &lt;p&gt;Ideally this data would help another developer track down the source of the error. &lt;/p&gt;      &lt;p&gt;But an entirely new exception is not needed to achieve this goal. The base Exception class contains a property named &lt;a href="http://msdn.microsoft.com/en-us/library/system.exception.data.aspx"&gt;Data&lt;/a&gt; which is an open dictionary. Any code which raises an exception is free to add custom data into the exception. This data can then be accessed by the handling code. Unique values still need to be dealt with. But in my experience, accessing a GUID based custom property is a bit more accepted than catching an exception based on some GUID property. &lt;/p&gt;      &lt;p&gt;This is especially true now with extension methods. The lack of type safety in the dictionary and potentially constant string sharing for property names could be hidden inside an extension method&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;No existing exception adequately described my problem      &lt;p&gt;I'd argue against this because of &lt;a href="http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx"&gt;InvalidOperationException&lt;/a&gt;. Invalid operation should cover most exceptional cases&lt;/p&gt;   &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;So of these reasons only #1 is a stand alone benefit of a new exception.&amp;#160; Now lets re-state this advantage in the context of the original question. &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Creating a new exception allows a developer to catch them &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Simple right?&amp;#160; But what benefit does this give to a developer?&amp;#160; From my experience there are only two reasons to catch an exception.&amp;#160; &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;It's a particular for which the underlying exceptional problem can be corrected.&amp;#160; Perhaps the user is prompted to fix the condition by performing some outside action (like re-inserting a disk).&lt;/li&gt;    &lt;li&gt;Logging errors for post-mortem debugging.&amp;#160; Note: You could also use the Data dictionary and extension methods above to introduce a new method ShouldLog().&amp;#160; This would allow you to avoid creating a new exception type.&amp;#160; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now I think we can answer the original question of this blog post.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;You should only create a new exception if you expect developers to take corrective action for the problem or to log for post mortem debugging.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Otherwise, what benefit does creating this exception give you?&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8997282" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</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>Immutability and ReadOnlyCollection&lt;T&gt;</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/22/api-design-readonlycollection-t.aspx</link><pubDate>Tue, 22 Apr 2008 15:42:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8415163</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8415163.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8415163</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8415163</wfw:comment><description>&lt;P&gt;I am a huge fan of read only/immutable collections and data.&amp;nbsp; Hopefully the increased exposure through the blogosphere alerted users to the advantages of this type of programming for the appropriate scenarios.&amp;nbsp; I wanted to discuss &lt;A href="http://msdn2.microsoft.com/en-us/library/ms132474.aspx" mce_href="http://msdn2.microsoft.com/en-us/library/ms132474.aspx"&gt;ReadOnlyCollection&amp;lt;T&amp;gt;&lt;/A&gt;&amp;nbsp;in case devs looking around in the BCL discover&amp;nbsp;it and assume it's immutable.&amp;nbsp; There are two details of this class which cause gotchas and design issues for consumers who assume it is immutable.&lt;/P&gt;
&lt;H3&gt;It implements IList&amp;lt;T&amp;gt;&lt;/H3&gt;
&lt;P&gt;&lt;A href="http://msdn2.microsoft.com/en-us/library/5y536ey6.aspx" mce_href="http://msdn2.microsoft.com/en-us/library/5y536ey6.aspx"&gt;IList&amp;lt;T&amp;gt;&lt;/A&gt; is a interface describing mutable collection types which support indexing.&amp;nbsp; ReadOnlyCollection is designed to be read only and cannot fulfill this contract.&amp;nbsp; Therfore every mutable function will throw an exception.&amp;nbsp; IMHO this is not the best design because it is&amp;nbsp;implementing a contract it won't every fullfill.&amp;nbsp; This has the effect of turning what should be a compile time error into a runtime exception (passing a non-mutable collection to an API expecting a mutable collection).&lt;/P&gt;
&lt;P&gt;Unfortunately there is not a good interface to implement.&amp;nbsp; The indexable interfaces are all representative of mutable collection types.&amp;nbsp; It would be nice to add an immutable/read only interface which can be safely implemented.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;interface&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;IReadOnlyList&lt;/SPAN&gt;&amp;lt;T&amp;gt; : &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;IEnumerable&lt;/SPAN&gt;&amp;lt;T&amp;gt;
    {
        T &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;this&lt;/SPAN&gt;[&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; index] { &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;get&lt;/SPAN&gt;; }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; Count { &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;get&lt;/SPAN&gt;; }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; IndexOf(T value);
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; Contains(T item);
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; CopyTo(T[] array, &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; arrayIndex);
    }&lt;/PRE&gt;
&lt;P&gt;Ideally this would be called IImmutableList&amp;lt;T&amp;gt; but I'm having trouble getting over the double I, double M pattern to start the name.&amp;nbsp; Perhaps IPersistentList.&lt;/P&gt;
&lt;H3&gt;It's not deeply ReadOnly&lt;/H3&gt;
&lt;P&gt;ReadOnlyCollection&amp;lt;T&amp;gt; is a read only facade on top of mutable collection.&amp;nbsp; Read only data should be just that, read only.&amp;nbsp; This means calling methods directly on the class produce the same result every single time.&amp;nbsp; However because it uses a mutable backing store this is not true and can cause gotchas along the road. &lt;/P&gt;
&lt;P&gt;Take the following sample which uses a ReadOnlyCollection to wrap a List.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; list = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;List&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;();
            list.AddRange(&lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Enumerable&lt;/SPAN&gt;.Range(1, 10));

            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; roList = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ReadOnlyCollection&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;(list);
            &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Console&lt;/SPAN&gt;.WriteLine(roList.Count);    &lt;SPAN style="COLOR: rgb(0,128,0)"&gt;// Outputs: 10
&lt;/SPAN&gt;            list.Add(42);
            &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Console&lt;/SPAN&gt;.WriteLine(roList.Count);    &lt;SPAN style="COLOR: rgb(0,128,0)"&gt;// Outputs: 11&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;There are ways to avoid this problem with ReadOnlyCollectionn.&amp;nbsp; The simplest is to make sure you pass a copy of your list into the constructor.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; roList2 = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ReadOnlyCollection&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;List&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;(list));&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8415163" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>Design Guidelines: Provide type inference friendly Create function for generic objects</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/11/design-guidelines-provide-type-inference-friendly-create-function-for-generic-objects.aspx</link><pubDate>Fri, 11 Apr 2008 15:24:50 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8363462</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8363462.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8363462</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8363462</wfw:comment><description>&lt;p&gt;Really this guideline is a bit longer but putting it all in a blog title seemed a bit too much.&amp;#160; The full guideline should read: &amp;quot;If a generic class constructor arguments contain types of all generic parameters, provide a static method named Create on a static class of the same class name as the generic class which takes the same arguments and calls the constructor.&amp;quot;&amp;#160; Quite a mouth full.&amp;#160; &lt;/p&gt;  &lt;p&gt;Lets look at a specific example with &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/01/27/tuples-part-8-finishing-up.aspx"&gt;Tuples&lt;/a&gt;.&amp;#160; Tuples are generic with respect to the values they are representing.&amp;#160; Without any type inference help we would have to write the following code to create a simple tuple. &lt;/p&gt;  &lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;&amp;gt;(5, &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;astring&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;p&gt;Not too bad because we are using simple types.&amp;#160; But what happens when we are using really long type names?&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple2 = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;,&lt;span style="color: rgb(43,145,175)"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;, &lt;span style="color: rgb(43,145,175)"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt;(val1, val2);&lt;/pre&gt;

&lt;p&gt;As we can see, the code is getting quite a bit uglier.&amp;#160; This pattern is in fact not maintainable once we start using un-namable types such as anonymous types or generics of anonymous types.&amp;#160; &lt;/p&gt;

&lt;p&gt;The problem here is we are not leveraging the compilers type inference capabilities.&amp;#160; The compiler can easily infer the types of a tuple argument and hence create a tuple.&amp;#160; We just need to provide a mechanism to do so.&amp;#160; The best way is to define a static method on a static class with the same name as the generic.&amp;#160; Lets call this method Create.&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt; {
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt; Create&amp;lt;TA, TB&amp;gt;(TA valueA, TB valueB) { 
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt;(valueA, valueB); 
        }
    }&lt;/pre&gt;

&lt;p&gt;The method Tuple.Create still has two generic parameters.&amp;#160; However since we are providing a set of values which contain types for every generic parameter, the compiler can infer the generic arguments.&amp;#160; Now we can create a Tuple without specifying any generic arguments.&amp;#160; Because no types are specified this will work with any value in the code including un-namable types.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple = &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;.Create(6, &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;astring&amp;quot;&lt;/span&gt;);
            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple2 = &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;.Create(6, &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; { name = &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;aname&amp;quot;&lt;/span&gt;, value = 42 });&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=8363462" 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/Patterns/default.aspx">Patterns</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/API+Design/default.aspx">API Design</category></item><item><title>Reference values in C++</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/03/reference-values-in-c.aspx</link><pubDate>Thu, 03 Apr 2008 17:24:54 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8345947</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8345947.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8345947</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8345947</wfw:comment><description>&lt;p&gt;Reference values are a powerful feature of C++ but I find they have one significant detractor.&amp;nbsp; A developer can not look at an API call and determine if a parameter is being passed by reference or value (VB has the same problem).&amp;nbsp; &lt;/p&gt; &lt;p&gt;IMHO this is one item that C# got 100% correct.&amp;nbsp; In C# developers must say a value is out/ref or a compile error results.&amp;nbsp; Forcing both the API declaration and usage to specify the reference semantics makes code much more understandable.&amp;nbsp; When you look at an API call there is absolutely no question about the byref/byval/out semantics of a parameter.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Internally I've met people who are hesitant to use reference parameters in C++ because of the ambiguity.&amp;nbsp; Not making it declarative in both places meant unexpected behavior could occur in a number of scenarios.&amp;nbsp; I agree with this statement.&amp;nbsp; &lt;/p&gt; &lt;p&gt;But hey we're talking about C++ here.&amp;nbsp; Any C++ problem can be fixed with some macros and a template right?&amp;nbsp; I thought about this over the weekend and came up with a quick sample.&amp;nbsp; Note, I haven't extensively tested this sample yet so there may be bugs.&amp;nbsp; However it gets the base cases right.&lt;/p&gt; &lt;p&gt;The goal of this API is to allow API authors to force developers to be explicit about their ByRef semantics.&amp;nbsp; It will prevent developers from silently passing a value by ref and hence getting unexpected behavior.&amp;nbsp; Failure to do so will result in a compile time error.&amp;nbsp; Also there is a minor bit of indirection overhead for debug mode but in retail this will compile out to normal code.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;#ifdef&lt;/span&gt; DEBUG

&lt;span style="color: rgb(0,0,255)"&gt;template&lt;/span&gt; &amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;typename&lt;/span&gt; T&amp;gt;
&lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; ByRefType
{
&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt;:
    &lt;span style="color: rgb(0,0,255)"&gt;explicit&lt;/span&gt; ByRefType(T&amp;amp; arg) : m_ref(arg)
    {
    }

    &lt;span style="color: rgb(0,0,255)"&gt;operator&lt;/span&gt; T&amp;amp;() &lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; 
    {
        &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; m_ref;
    }

    ByRefType&amp;amp; &lt;span style="color: rgb(0,0,255)"&gt;operator&lt;/span&gt;=(&lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; T&amp;amp; value)
    {
        m_ref = value;
        &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; *&lt;span style="color: rgb(0,0,255)"&gt;this&lt;/span&gt;;
    }

&lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt;:
    ByRefType();

    &lt;span style="color: rgb(0,0,255)"&gt;mutable&lt;/span&gt; T&amp;amp; m_ref;
};

&lt;span style="color: rgb(0,0,255)"&gt;template&lt;/span&gt; &amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;typename&lt;/span&gt; T&amp;gt;
ByRefType&amp;lt;T&amp;gt; MakeByRefType(T&amp;amp; expr)
{
    &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; ByRefType&amp;lt;T&amp;gt;(expr);
}

&lt;span style="color: rgb(0,0,255)"&gt;#define&lt;/span&gt; ByRef(expr) MakeByRefType(expr)
&lt;span style="color: rgb(0,0,255)"&gt;#define&lt;/span&gt; ByRefParam(type) ByRefType&amp;lt;type&amp;gt; 

&lt;span style="color: rgb(0,0,255)"&gt;#else

&lt;/span&gt;&lt;span style="color: rgb(128,128,128)"&gt;#define ByRef(expr) expr
#define ByRefParam(type) type&amp;amp;

&lt;/span&gt;&lt;span style="color: rgb(0,0,255)"&gt;#endif&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;All well and good.&amp;nbsp; Now we can attribute byref paramaters with ByRefParam() and force callers to tag it as a ByRef argument.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; SimpleByRef(ByRefParam(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;) i, &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; newValue)
{
    i = newValue;
}

&lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Test()
{
    &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; i1;
    SimpleByRef(ByRef(i1), 5);
    SimpleByRef(i1, 6);     &lt;span style="color: rgb(0,128,0)"&gt;// Compiler Error!!!
&lt;/span&gt;}&lt;/pre&gt;As said before, this is an initial implementation and I expect updates as I use this in code and find bugs.&amp;nbsp; Please post back with any you find.&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8345947" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Templates/default.aspx">Templates</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>API Problems: CComObject::CreateInstance</title><link>http://blogs.msdn.com/jaredpar/archive/2008/03/28/api-problems-ccomobject-createinstance.aspx</link><pubDate>Sat, 29 Mar 2008 02:38:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8342588</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8342588.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8342588</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8342588</wfw:comment><description>&lt;P&gt;&lt;A href="http://msdn2.microsoft.com/en-us/library/9e31say1.aspx" mce_href="http://msdn2.microsoft.com/en-us/library/9e31say1.aspx"&gt;CComObject::CreateInstance&lt;/A&gt; is a light weight method for creating instances of COM objects in your code.&amp;nbsp; Unfortunately the design of the API makes it easy to introduce subtle errors into your code.&amp;nbsp; The two problems are it encourages manually ref counting and the object initially has a ref count of 0.&amp;nbsp; This means you must remember to AddRef before calling any other function. Neither of these ideas in themselves are bad but it leads to tedious, repetitive code that is too often done incorrectly.&lt;/P&gt;
&lt;P&gt;Below is a typical example I see in code. &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AMethod()
{
    CComObject&amp;lt;Student&amp;gt; *pStudent;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; ( SUCCEEDED(CComObject&amp;lt;Student&amp;gt;::CreateInstance(&amp;amp;pStudent)) )
    {
        pStudent-&amp;gt;AddRef();
        VerifyStudent(pStudent);
        pStudent-&amp;gt;Release();
    }
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;As a result of the manual ref counting, this code is not exception safe.&amp;nbsp; If VerifyStudent or any API it calls throws, an instance of Student will be leaked.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;The second problem I often see in code is the placement of the VerifyStudent function.&amp;nbsp; Occasionally I see methods like VerifyStudent called before the AddRef.&amp;nbsp; If you see this in your code immediately file a bug.&amp;nbsp; The problem is the ref count is 0 before you call AddRef.&amp;nbsp; It COM it should always be legal to AddRef/Release a COM object passed into your function.&amp;nbsp; In this case while legal it will destroy the instance of Student.&amp;nbsp; What's even worse is this bug can show up years after you code.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Real world example.&amp;nbsp; I created a class to wrap a couple of operations.&amp;nbsp; One of it's members was Student and as such I wrapped it in a CComPtr&amp;lt;&amp;gt; for ease of use.&amp;nbsp; Fired up the program and everything crashed.&amp;nbsp; Turns out an instance of Student was passed to a function that eventually created an instance of my object before AddRef was called (essentially move VerifyStudent up one line).&amp;nbsp; As soon as my new object died CComPtr&amp;lt;&amp;gt; called Release, moved the RefCount to 0 and destroyed the object.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Writing the correct code is repetitive and begs for a wrapper function.&amp;nbsp; Enter CreateWithRef&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;template&lt;/SPAN&gt; &amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;class&lt;/SPAN&gt; T&amp;gt;
&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;static&lt;/SPAN&gt; 
HRESULT CreateWithRef(T** ppObject)
{
    CComObject&amp;lt;T&amp;gt; *pObject;
    HRESULT hr = CComObject&amp;lt;T&amp;gt;::CreateInstance(&amp;amp;pObject);
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; ( SUCCEEDED(hr) )
    {
        pObject-&amp;gt;AddRef();
        *ppObject = pObject;
    }

    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; hr; 
}

&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AMethod2()
{
    CComPtr&amp;lt;Student&amp;gt; pStudent;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; ( SUCCEEDED(CreateWithRef(&amp;amp;pStudent)) )
    {
        VerifyStudent(pStudent);
    }
}&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;As you can see, using this function takes less typing that a normal CreateInstance due to using type inference.&amp;nbsp; It's also exception safer since the resource is managed.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;This API still has one flaw.&amp;nbsp; It allows people to pass in a raw pointer and hence violate exception safety.&amp;nbsp; It could be improved by forcing a caller to pass in a class which supports &lt;A href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" mce_href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization"&gt;RAII&lt;/A&gt;.&amp;nbsp; In this case a good choice is CComPtrBase&amp;lt;&amp;gt;.&amp;nbsp; I tend to prefer this design because it forces the caller to use safer code.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;template&lt;/SPAN&gt; &amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;class&lt;/SPAN&gt; T&amp;gt;
&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;static&lt;/SPAN&gt; 
HRESULT CreateWithRef2(CComPtrBase&amp;lt;T&amp;gt;&amp;amp; spPointer)
{
    CComObject&amp;lt;T&amp;gt; *pObject;
    HRESULT hr = CComObject&amp;lt;T&amp;gt;::CreateInstance(&amp;amp;pObject);
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; ( SUCCEEDED(hr) )
    {
        pObject-&amp;gt;AddRef();
        spPointer.Attach(pObject);
    }

    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; hr; 
}

&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; AMethod3()
{
    CComPtr&amp;lt;Student&amp;gt; pStudent;
    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;if&lt;/SPAN&gt; ( SUCCEEDED(CreateWithRef2(pStudent)) )
    {
        VerifyStudent(pStudent);
    }
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8342588" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item></channel></rss>