<?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</title><link>http://blogs.msdn.com/jaredpar/default.aspx</link><description>Code, rants and ramblings of a programmer.</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Vim Emulator Editor For Beta2 Released</title><link>http://blogs.msdn.com/jaredpar/archive/2009/11/16/vim-emulator-editor-for-beta2-released.aspx</link><pubDate>Tue, 17 Nov 2009 04:17:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9923415</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9923415.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9923415</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9923415</wfw:comment><description>&lt;p&gt;This is essentially the same release as the &lt;a href="http://blogs.msdn.com/jaredpar/archive/2009/09/08/vim-emulator-editor-extension-released.aspx"&gt;original&lt;/a&gt; but updated for some changes that occurred in the APIs between Beta1 and Beta2.&amp;#160; &lt;/p&gt;  &lt;p&gt;Link: &lt;a href="http://visualstudiogallery.msdn.microsoft.com/en-us/59ca71b3-a4a3-46ca-8fe1-0e90e3f79329"&gt;http://visualstudiogallery.msdn.microsoft.com/en-us/59ca71b3-a4a3-46ca-8fe1-0e90e3f79329&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The biggest change came in the way in which Visual Studio routes commands.&amp;#160; Vim, as you can imagine, needs to participate in command routing and these changes took awhile to sort out.&amp;#160; I believe I’ve sorted out the issues but please send me a mail / comment if you find any bugs.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;b&gt;Caveats and Expectations&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;This extension is being released by me, not by Microsoft.&amp;#160; As such the support level for this extension is equivalent to the amount of free time I have to put into it. &lt;/p&gt;  &lt;p&gt;&lt;b&gt;What’s next?&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;Right now the Visual Studio command system is the biggest inhibitor to implementing new features.&amp;#160; Each command in Visual Studio is bound to a specific key stroke and often times this conflicts with key strokes my Vim emulator needs to process.&amp;#160; &lt;/p&gt;  &lt;p&gt;It’s easy to implement these commands in the core Vim engine.&amp;#160; However the actual key strokes get intercepted by Visual Studio and are not processed.&lt;/p&gt;  &lt;p&gt;My next feature will be essentially removing these commands so that they can make it to the Vim layer.&amp;#160; It will require a bit of a UI since I’ll be essentially changing key bindings but hopefully I can get something basic out the door so that I can start focusing on real features again.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9923415" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VsVim/default.aspx">VsVim</category></item><item><title>Type safety issue when assigning CComPtr&lt;T&gt; instances</title><link>http://blogs.msdn.com/jaredpar/archive/2009/11/04/type-safety-issue-when-assigning-ccomptr-t-instances.aspx</link><pubDate>Wed, 04 Nov 2009 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9916908</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9916908.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9916908</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9916908</wfw:comment><description>&lt;p&gt;Recently while making a bug fix to our selection tracking code I discovered an unexpected behavior with CComPtr&amp;lt;T&amp;gt; instances.&amp;#160; The crux of the fix included creating a new tracking mechanism exposed via COM in the type ISelectionTracking.&amp;#160; The old interface, lets call it IOldTracking, was a completely unrelated interface in terms of inheritance hierarchies.&amp;#160; &lt;/p&gt;  &lt;p&gt;As part of the fix I changed the type of a field (m_spTracking) from CComPtr&amp;lt;IOldTracking&amp;gt; to CComPtr&amp;lt;ISelectionTracking&amp;gt;.&amp;#160; I searched for assignments of m_spTracking and converted them to call the new API I added as part of the fix.&amp;#160; I didn’t search terribly hard because I was depending on the compiler to catch any places I missed.&amp;#160; ISelectionTracking and IOldTracking are incompatible types so any places I missed will show up as compilation errors.&amp;#160; &lt;/p&gt;  &lt;p&gt;Or so I thought … &lt;/p&gt;  &lt;p&gt;I made my fix, ran our core check-in suites without error, checked in and moved onto the next bug.&amp;#160; A couple hours later one of our other devs emailed me and informed me my check-in was breaking our larger, slower, suite bed run because m_spTracking was NULL. After some quick debugging I found myself looking at the following chunk of code which was apparently NULL’ing out m_spTracking in the suite.&lt;/p&gt;  &lt;pre class="code"&gt;  CComPtr&amp;lt;IOldTracking&amp;gt; spOldTracking;
&lt;span style="color: blue"&gt;  if &lt;/span&gt;( SUCCEEDED(CreateOldSelectionTracking(&amp;amp;spOldTracking)) ) {
    m_spTracking = spOldTracking;
  }
 &lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Me and the other dev were quite shocked that this compiled at all.&amp;#160; How is it possible to assign between CComPtr&amp;lt;ISelectionTracking&amp;gt; and CComPtr&amp;lt;IOldTracking&amp;gt;???&amp;#160; My first thought was I must have accidentally used a CComQIPtr somewhere (quickly verified that was not the case).&amp;#160; After a bit of searching we found the cause was one of the operater=&amp;#160; instances available on CComPtr&amp;lt;T&amp;gt;.&amp;#160; Here is the definition&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;template &lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;typename &lt;/span&gt;Q&amp;gt;
T* &lt;span style="color: blue"&gt;operator&lt;/span&gt;=(_In_ &lt;span style="color: blue"&gt;const &lt;/span&gt;CComPtr&amp;lt;Q&amp;gt;&amp;amp; lp) &lt;span style="color: blue"&gt;throw&lt;/span&gt;()
{
    &lt;span style="color: blue"&gt;if&lt;/span&gt;( !IsEqualObject(lp) )
    {
        &lt;span style="color: blue"&gt;return static_cast&lt;/span&gt;&amp;lt;T*&amp;gt;(AtlComQIPtrAssign((IUnknown**)&amp;amp;p, lp, &lt;span style="color: blue"&gt;__uuidof&lt;/span&gt;(T)));
    }
    &lt;span style="color: blue"&gt;return &lt;/span&gt;*&lt;span style="color: blue"&gt;this&lt;/span&gt;;
}&lt;/pre&gt;

&lt;p&gt;This templated operator allows for assignments between CComPtr instance no matter what the type is for the left and right side.&amp;#160; The effect is that instead of doing compile type C++ type conversion rules, it will instead rely on runtime COM polymorphic assignment rules via IUnknown::QueryInterface.&amp;#160; This moves assignment errors from compile time to runtime for unrelated interfaces.&amp;#160; &lt;/p&gt;

&lt;p&gt;This is further complicated because it only applies to assignment between CComPtr’s (and derived instances).&amp;#160; If the right hand side of the assignment is a non-smart pointer, compile time C++ conversions will apply.&amp;#160; To demonstrate …&lt;/p&gt;

&lt;pre class="code"&gt;        CComPtr&amp;lt;ISelectionTracking&amp;gt; spTracking;
        CComPtr&amp;lt;IOldTracking&amp;gt; spOld;
        ...
        spTracking = spOld;  &lt;span style="color: green"&gt;// Fails at runtime
        &lt;/span&gt;spTracking = (IOldTracking*)spOld;  &lt;span style="color: green"&gt;// Compilation Error
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;What surprised me though was talking to other developers about this issue.&amp;#160; Most agreed with me that this is a bug in CComPtr&amp;lt;T&amp;gt;, or at least very unexpected behavior.&amp;#160; A surprising number though did not expect this behavior but still considered it acceptable.&amp;#160; The difference comes down whether you view CComPtr&amp;lt;T&amp;gt; as a simple smart pointer responsible for AddRef/Release semantics or as that plus an enabler of QueryInterface style conversions.&amp;#160; I personally view CComPtr&amp;lt;T&amp;gt; as a simple smart pointer with know real understanding of QueryInterface style conversions and CComQIPtr&amp;lt;T&amp;gt; as a smart pointer which respects QueryInterface style conversions.&amp;#160;&amp;#160; As such this behavior is completely unexpected.&amp;#160; &lt;/p&gt;

&lt;p&gt;The fix in this case was pretty straight forward (use the new API) but I was still worried about how to prevent this type of problem in the future.&amp;#160; In particular how to get the failure back to a compile time error.&amp;#160; In the end we settled on using a stripped down version of CComPtr we already had in our code base going forward called CComPtrEx.&amp;#160; I’ve previously blogged about about the need for this type &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/02/22/multiple-paths-to-iunknown.aspx"&gt;here&lt;/a&gt;.&amp;#160; It’s different from CComPtr in the following ways&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Does not have the templated version of operator= and instead relies on compile time C++ conversions checks for assignment &lt;/li&gt;

  &lt;li&gt;Allows for interfaces which have multiple paths to IUnknown (can cause a compile time error in CComPtr). &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Also for purposes of rigor, we temporarily commented out the CComPtr&amp;lt;T&amp;gt; operator, recompiled our code base and verified no new errors popped up.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9916908" 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/Gotcha/default.aspx">Gotcha</category></item><item><title>Speaking at Dev Connections in Las Vegas Next Week</title><link>http://blogs.msdn.com/jaredpar/archive/2009/11/03/speaking-at-dev-connections-in-las-vegas-next-week.aspx</link><pubDate>Tue, 03 Nov 2009 16:51:04 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9916831</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9916831.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9916831</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9916831</wfw:comment><description>&lt;p&gt;Next week I will be speaking at &lt;a href="http://www.devconnections.com/shows/FALL2009VS/default.asp?s=136"&gt;Dev Connections&lt;/a&gt; in Las Vegas.&amp;#160; I will be running the following sessions&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;VMS02: Future Directions for Visual Basic&lt;/li&gt;    &lt;li&gt;VMS04: Microsoft Visual Basic IDE Tips and Tricks&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Both of these talks will spend a bit of time talking about all of the progress and exciting new features we’ve added in Dev10.&amp;#160; Given I primarily work on the IDE these days, expect a bit of IDE content to work it’s way into the Future Directions talk as well.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9916831" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category></item><item><title>Using F# Discriminated Unions in C# (Beta2)</title><link>http://blogs.msdn.com/jaredpar/archive/2009/10/27/using-f-discriminated-unions-in-c-beta2.aspx</link><pubDate>Tue, 27 Oct 2009 12:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9913363</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9913363.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9913363</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9913363</wfw:comment><description>&lt;p&gt;While updating my VsVim editor extensions for Beta2 [1] I got hit by a change in the way F# exposed discriminated unions in metadata.&amp;#160; My extension consists of a core F# component with a corresponding set of unit tests written in C#.&amp;#160; It’s mostly API level testing and as such I use a lot of F# generated types in my C# test assembly.&lt;/p&gt;  &lt;p&gt;In Beta1 all information which could be extracted from a discriminated type union was immediately available on the value.&amp;#160; The underlying type presentation was less than desirable but these details were hidden by type inference and the very accessible API.&amp;#160;&amp;#160; The type wasn’t perfect because given a particular instance only the subset of the properties relevant to the union value type were valid.&amp;#160; All others threw exceptions.&amp;#160; But the code use of these methods and properties flowed very well.&amp;#160;&amp;#160; &lt;/p&gt;  &lt;p&gt;For instance take the following F# definition&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;ActionKind =
    | Mouse = &lt;span style="color: brown"&gt;1
    &lt;/span&gt;| Keyboard = &lt;span style="color: brown"&gt;2

&lt;/span&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;ActionResult =
    | Complete &lt;span style="color: blue"&gt;of &lt;/span&gt;(ActionKind * int)
    | Error &lt;span style="color: blue"&gt;of &lt;/span&gt;string
    | NeedMore &lt;span style="color: blue"&gt;of &lt;/span&gt;(char &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;ActionResult)&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The use case in C# was quite simple&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;TestActionBeta1(){
    &lt;span style="color: blue"&gt;var &lt;/span&gt;res = GetResult();
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(res.IsComplete());
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: #2b91af"&gt;ActionKind&lt;/span&gt;.Mouse, res.Complete1.Item1);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: brown"&gt;42&lt;/span&gt;, res.Complete1.Item2);
}&lt;/pre&gt;

&lt;p&gt;Notice how no type information is necessary and the code flows quite naturally.&amp;#160; C# type inference works great here and allows me to do what I need to do without fussing around with little stuff.&amp;#160; The type in this case is a detail I don’t need to know about.&amp;#160; It simply adds no value.&amp;#160; &lt;/p&gt;

&lt;p&gt;Discriminated Unions in Beta2 changed substantially in this area.&amp;#160; Instead of generating the set of all values on the exposed type, there is now an inner type generated for every discriminated union value and the properties relevant to that union value are stored on the inner type.&amp;#160; The outer type now contains only properties to determine which type of value it is (certainly an upgrade from methods!) [2]&lt;/p&gt;

&lt;p&gt;For instance in the case of ActionResult there are 3 generated inner classes: Complete, Error and NeedMore.&amp;#160; Each one contains a single property Item which contains the associated value(s).&amp;#160; This means to get to the value portion a cast to the inner type must be inserted!&amp;#160; &lt;/p&gt;

&lt;p&gt;Lets take a a look at how the above test code has to change to deal with the Beta2 generation of ActionResult.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;TestActionBeta2() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;res = GetResult();
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(res.IsComplete);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: #2b91af"&gt;ActionKind&lt;/span&gt;.Mouse, ((&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete&lt;/span&gt;)res).Item.Item1);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: brown"&gt;42&lt;/span&gt;, ((&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete&lt;/span&gt;)res).Item.Item2);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Notice the explicit casts which must be added to access the values.&amp;#160; This makes it impossible to rely soley on C# type inference.&amp;#160; I must now understand the underlying type structure of discriminated unions in order to use them.&amp;#160; This extra cast adds no real value to my code.&amp;#160; &lt;/p&gt;

&lt;p&gt;My C# test assembly has literally hundreds of test cases which use this pattern on F# types.&amp;#160; I didn’t know the return type of every method and found myself hitting “Goto Def” on a lot of “var” instances to discover the static type, going back to the original file and inserting the cast.&amp;#160; It was a tedious and slow process.&lt;/p&gt;

&lt;p&gt;Eventually I settled on a different solution.&amp;#160; For every type I exposed in F# I added a set of extension methods in the form of AsXXX where XXX represented the name of the generated inner types.&amp;#160;&amp;#160; For example&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete &lt;/span&gt;AsComplete(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult &lt;/span&gt;res) {
    &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete&lt;/span&gt;)res;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The advantage of this approach is 2 fold &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Removes the need to explicitly name types in code and hence gets back the advantages of type inference&lt;/li&gt;

  &lt;li&gt;I can now use . on any of the values and let Intellisense help me find the appropriate method to use&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This extension method allows me to get closer to the Beta1 style code &lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;TestActionBeta2() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;res = GetResult();
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(res.IsComplete);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: #2b91af"&gt;ActionKind&lt;/span&gt;.Mouse, res.AsComplete().Item.Item1);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: brown"&gt;42&lt;/span&gt;, res.AsComplete().Item.Item2);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;With these methods and a quick series of Find / Replace calls, I was back in business.&amp;#160; &lt;/p&gt;

&lt;p&gt;[1] It’s coming I promise!&amp;#160; &lt;/p&gt;

&lt;p&gt;[2] It also contains a handy set of factory methods for generating values but it’s not relevant to this discussion.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9913363" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Extension+Methods/default.aspx">Extension Methods</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/F_2300_/default.aspx">F#</category></item><item><title>Vim Emulator Editor Extension Released</title><link>http://blogs.msdn.com/jaredpar/archive/2009/09/08/vim-emulator-editor-extension-released.aspx</link><pubDate>Wed, 09 Sep 2009 05:09:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9863823</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>15</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9863823.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9863823</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9863823</wfw:comment><description>&lt;p&gt;I just released version 0.5.0 of VsVim: a vim emulation editor extension for Visual Studio 2010 Beta1 written in F#.&amp;nbsp; This is a hobby project I’ve been working on for awhile now.&amp;nbsp; I expect to continue updating this release as time goes on as I use it on a daily basis and I’m interested in getting back feedback from users on it.&amp;nbsp;&amp;nbsp;&lt;/p&gt;&lt;p&gt;Link:&amp;nbsp;&lt;a href="http://visualstudiogallery.msdn.microsoft.com/en-us/59ca71b3-a4a3-46ca-8fe1-0e90e3f79329"&gt;http://visualstudiogallery.msdn.microsoft.com/en-us/59ca71b3-a4a3-46ca-8fe1-0e90e3f79329&lt;/a&gt;&amp;nbsp;&lt;/p&gt;  &lt;p&gt;Here’s a quick break down on the state of this project&lt;/p&gt;  &lt;p align="left"&gt;&lt;b&gt;Caveats and Expectations&lt;/b&gt;&lt;/p&gt;  &lt;p align="left"&gt;This extension is being released by me, not by Microsoft.&amp;nbsp; As such the support level for this extension is equivalent to the amount of free time I have to put into it.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;&lt;b&gt;Quality Level&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;I would classify this as a Beta style release.&amp;nbsp; I use this extension every day and I have a very large test bed to verify functionality.&amp;nbsp; There are still several known bugs (detailed below) and little quirks I’m working on.&amp;nbsp; But they are mostly minor issues&lt;/p&gt;  &lt;p&gt;&lt;b&gt;What’s Implemented&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;At this point the engine has an Insert, Normal and Command mode.&amp;nbsp; &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;     &lt;div align="left"&gt;Insert Mode&lt;/div&gt;      &lt;ul&gt;       &lt;li&gt;         &lt;div align="left"&gt;Basic insertion layer which allows for typing.&amp;nbsp; No special insert mode commands are implemented &lt;/div&gt;       &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;div align="left"&gt;Normal Mode.&lt;/div&gt;      &lt;ul&gt;       &lt;li&gt;Movement Commands: h,j,k,l,w,b,$,^,n,*,# &lt;/li&gt;        &lt;li&gt;Edit Commands: x,X,d,p,P,A,u,&amp;lt;,&amp;gt;,o &lt;/li&gt;        &lt;li&gt;Incremental Search &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;div align="left"&gt;Command Mode&lt;/div&gt;      &lt;ul&gt;       &lt;li&gt;         &lt;div align="left"&gt;:e&lt;/div&gt;       &lt;/li&gt;        &lt;li&gt;         &lt;div align="left"&gt;Jump to line&lt;/div&gt;       &lt;/li&gt;        &lt;li&gt;         &lt;div align="left"&gt;Beginning / end of line&lt;/div&gt;       &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt; &lt;/ul&gt;  &lt;p align="left"&gt;&lt;b&gt;Deviations &lt;/b&gt;&lt;/p&gt;  &lt;p align="left"&gt;The biggest deviation I made from a traditional VIM engine is that I am using .Net regular expressions instead of VIM style regular expressions.&amp;nbsp; This allowed me to focus on getting a lot of features written vs. spending time building a regular expression engine.&amp;nbsp; Getting this working will be a focus of a later release.&amp;nbsp; &lt;/p&gt;  &lt;p align="left"&gt;Another issue is the cursor.&amp;nbsp; As flexible as the new editor is, one part that is very tricky is changing the appearance of the cursor.&amp;nbsp; So making a block style cursor for normal mode was not done for this release.&amp;nbsp; Instead I simply color the cursor red for normal mode and black for insert mode.&amp;nbsp; This will be fixed in a later release.&lt;/p&gt;  &lt;p align="left"&gt;&lt;b&gt;Bugs&lt;/b&gt;&lt;/p&gt;  &lt;p align="left"&gt;Below is the list of known issues for the extension.&amp;nbsp; I’ve noted all bugs for which I cannot get a steady repro.&amp;nbsp; If you can find one I would appreciate you emailing the steps to me.&amp;nbsp; &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;     &lt;div align="left"&gt;Cursor appearance in normal mode is not a block cursor but instead a red cursor &lt;/div&gt;   &lt;/li&gt;    &lt;li&gt;Need Repro: Using ‘o’ in normal mode can cause the line ending to switch from \r\n to \r or \n. &lt;/li&gt;    &lt;li&gt;     &lt;div align="left"&gt;Both ‘#’ and ‘*’ match partial words instead of full words&lt;/div&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;div align="left"&gt;Register list is limited to standard a-z alphabet &lt;/div&gt;   &lt;/li&gt; &lt;/ul&gt;  &lt;p align="left"&gt;&lt;b&gt;What’s next?&lt;/b&gt;&lt;/p&gt;  &lt;p align="left"&gt;Thus far I’ve been working on features which don’t conflict with existing Visual Studio key bindings.&amp;nbsp; The next big release will be focusing on the infrastructure needed to integrate these commands smoothly into the core Vim engine and Visual Studio itself.&amp;nbsp; This will allow me to expand the number of implemented features a great deal.&amp;nbsp; &lt;/p&gt;  &lt;p align="left"&gt;&lt;b&gt;Where’s the source?&lt;/b&gt;&lt;/p&gt;  &lt;p align="left"&gt;Should be released soon.&amp;nbsp; Right now I’m working out where I should host this project long term.&amp;nbsp; Preferably a place where users can file bugs and leave feedback.&amp;nbsp; &lt;/p&gt;  &lt;p align="left"&gt;&lt;br&gt;&lt;/p&gt;  &lt;p align="left"&gt;&amp;nbsp;&lt;/p&gt;  &lt;p align="left"&gt;&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9863823" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/F_2300_/default.aspx">F#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VsVim/default.aspx">VsVim</category></item><item><title>Why is LINQ absent from debugger windows?</title><link>http://blogs.msdn.com/jaredpar/archive/2009/08/26/why-no-linq-in-debugger-windows.aspx</link><pubDate>Wed, 26 Aug 2009 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9877055</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9877055.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9877055</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9877055</wfw:comment><description>&lt;p&gt;As the owner of the VB.Net portion of the overall debugging experience, I frequently hear the request from customers to add LINQ support into the Watch / Immediate and Locals window.&amp;nbsp; Virtually every other type of expression is available in the debugger windows so why leave one of the most popular ones out? &lt;/p&gt;  &lt;p&gt;Quick Diversion: the specifics of this article are written from the point of view of the VB.Net expression evaluator.&amp;nbsp; However, the limitations blocking LINQ support (in both the architecture and overall design) are very similar between VB.Net and C#.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;As usual, the primary issue is cost and the cost for LINQ in the debugger windows is very high.&amp;nbsp; To understand why the cost is so high though, we must start by getting a better understanding how a language service interacts with the debugging services of Visual Studio and the general philosophy around compiler features in the debugger.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Languages in Visual Studio typically provide the following major components to support the debugging experience.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;     &lt;p&gt;Expression Evaluator (EE): This is the language specific component which provides all of the data used in the watch, locals and immediate window, data tips, conditional breakpoints and several other components.&amp;nbsp; It’s primary input is an expression in string form which is converted to a value (typically an ICorDebugValue instance) and outputs a COM object capable of inspecting that value to the core debugger [1].&amp;nbsp;&amp;nbsp; Everything typed into the debugger windows goes through the EE.&lt;/p&gt;      &lt;p&gt;This component lives in the MTA of Visual Studio and has almost no interaction with the UI / STA thread. &lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;ENC Service: This is the component which is the work horse of ENC operations.&amp;nbsp; It provides rude edit detection, metadata differencing and metadata + IL generation&amp;nbsp;&amp;nbsp; .&lt;/p&gt;      &lt;p&gt;This component lives in the main STA of Visual Studio&lt;/p&gt;   &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The important thing to understand about the expression evaluator is that it’s purpose is primarily to provide an expression evaluation and data inspection service.&amp;nbsp; How expression evaluation works is an article in itself but suffice it to say that it converts the string to a very low level AST then walks the nodes bottom up and evaluating the expressions using the ICorDebug APIs.&amp;nbsp; The EE component has no UI and is simply a data provider for the core debugger services.&amp;nbsp;&amp;nbsp; &lt;/p&gt;  &lt;p&gt;The design philosophy for Both VB.Net and C# is to have the highest level of fidelity between expressions evaluated in the EE and the actual running program.&amp;nbsp; To do otherwise would lead to extremely confusing results for users.&amp;nbsp; When spec’ing feature support in the VB.Net EE we start from the point of 100% fidelity, determine the problems with this design (if any) and then start the difficult process of making compromises.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;LINQ expressions are very different than any other expression previously allowed in the EE window because of the features interaction with metadata.&amp;nbsp; All LINQ expressions require the generation or manipulation of metadata to support the underlying lambda and/or closure.&amp;nbsp; Adding support for this is one of the biggest hurdles to getting LINQ (and other features) into the EE.&amp;nbsp;&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Evaluating a LINQ expression is actually much closer to an ENC operation than a traditional EE one.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Currently the EE’s have no capacity for generating metadata, only interpreting it.&amp;nbsp; Operations which mutate or generate metadata have traditionally only been allowed via the ENC service.&amp;nbsp; Getting LINQ to work in the EE with true fidelity would require at least a minimal amount of ENC feature work.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Without getting into too much detail, lets enumerate the&lt;b&gt; new&lt;/b&gt; major features necessary to evaluate a LINQ expression in the EE with true fidelity to the running program.&amp;nbsp; To simplify things, we’ll start by assuming there is no other LINQ expression used in the current method and the method is only being executed at most once at any given time in the process.&amp;nbsp;&amp;nbsp; &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;A metadata generation service to support the backing for closures and lambda expressions &lt;/li&gt;    &lt;li&gt;Convert expressions typed in the EE into IL [2] &lt;/li&gt;    &lt;li&gt;ENC support for metadata to push the new metadata for closures and lambdas into the currently executing assembly &lt;/li&gt;    &lt;li&gt;ENC support for method body IL to remove lifted variables from the current method and redirect the references inside the closure&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Issues #1 and #2 are for the most part internal architecture issues and can be solved via normal processes of code base refactoring and adding new features to an existing component.&amp;nbsp;&amp;nbsp; I don’t mean to imply these problems are cheap (in fact they are relatively expensive)&amp;nbsp; But fixing these is somewhat of an understood quantity.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Issues #3 and #4 are where the problems start.&amp;nbsp; As implemented EE’s do not have capability to create or modify metadata in the running process (that is the job of the ENC service).&amp;nbsp; EE’s do have access to the underlying CLR ENC APIs so it is possible to implement ENC operations in the EE.&amp;nbsp; It’s just simply not been done yet.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Wait!&amp;nbsp; Why not reuse our ENC implementation in the EE?&amp;nbsp; Unfortunately the ENC service is currently tied heavily to our in memory IDE compiler and many other IDE / STA features.&amp;nbsp; It in fact lives in a completely separate DLL, separate COM apartment and works on a different symbol table than the EE.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;More fundamental though is that it’s designed for a completely different purpose.&amp;nbsp; ENC is designed to track edits in live code, determining the differences and applying them to the running program.&amp;nbsp; The hypothetical EE feature would be tracking expressions that modify a running DLL for which code is not guaranteed (and not likely) to be available and applying the difference to the running program.&amp;nbsp; There are some similarities but the differences are significant enough to make code reuse have limited value.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Some people may wonder why it’s necessary to implement #4.&amp;nbsp; Couldn’t we just avoid removing the variable from the current method and make the feature cheaper?&amp;nbsp; This is possible but it would cause a significant fidelity difference in the feature.&amp;nbsp; Any mutations of the local variable within the LINQ expression would not be visible on the stack frame as it would if the LINQ expression was present in the original program.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;It’s easy to think of this ENC in the EE as just the same type of cost as #1 and #2 (in many ways it is).&amp;nbsp; However taking advantage of the CLR ENC APIs in the EE also means that we inherit it’s limitations as well.&amp;nbsp; ENC as as implemented in the CLR has many limitations which fly in the face of LINQ.&amp;nbsp; In particular the following ENC limitations present major problems (&lt;a mce_href="http://blogs.msdn.com/jmstall/archive/2005/02/19/376666.aspx" href="http://blogs.msdn.com/jmstall/archive/2005/02/19/376666.aspx"&gt;ENC limitations reference&lt;/a&gt;).&amp;nbsp; &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Cannot add members to a value type.&amp;nbsp; This prevents evaluating LINQ when stopped in a value type method &lt;/li&gt;    &lt;li&gt;Cannot remove locals from a function.&amp;nbsp; This is an implementation of LINQ but we could work around this problem by changing the IL to simply no longer accessing the local variables. &lt;/li&gt;    &lt;li&gt;Cannot change anything in a generic type.&amp;nbsp; This prevents evaluating LINQ when stopped in a generic type.&amp;nbsp; &lt;/li&gt;    &lt;li&gt;Cannot specify an initial value for newly added fields. &lt;/li&gt;    &lt;li&gt;Allowable ENC operations differ between the top of the stack and operations elsewhere within the stack &lt;/li&gt;    &lt;li&gt;Modification of a non-top stack frame cannot significantly edit the current function call.&amp;nbsp; So if a LINQ expression captures a variable used in that call (think ref passing) it would likely be unable to be evaluated.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;So even if we implemented everything possible on the language service side the resulting feature would be limited in several impactful ways.&amp;nbsp; Additionally these limitations are somewhat orthogonal to the current limitations EE’s face and would require a bit of user education.&amp;nbsp; And this is only for the most basic LINQ feature under unrealistic scenarios.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Lets now consider the problems of evaluating a LINQ expression when the current method already contains a LINQ expression that lifts at least 1 variable.&amp;nbsp; Evaluating a new expression at the same scope would require the modification of the current closure to maintain fidelity as opposed to generating a new one.&amp;nbsp; This brings along with it a couple more problems.&amp;nbsp; &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;     &lt;p&gt;A lambda expression which uses 2 variables, 1 of which is captured in an existing lambda expression.&amp;nbsp; To maintain fidelity we would have to modify an existing closure signature to contain the new variable. &lt;/p&gt;      &lt;p&gt;&amp;nbsp;&lt;/p&gt;      &lt;p&gt;Often times generated closures are generic so we would run straight into ENC limitation #3. Additionally we would need the newly added field to have the same value as it has in the current method which runs us into ENC limitation #4. Now also consider that a closure instance can live much longer than the method in which it was created. For those closures no stack value is available so what value should we give fields in that instance?&amp;nbsp; Ideally it should have the value of the variable at the point the method exited but realistically that’s not possible.&amp;nbsp; &lt;/p&gt;      &lt;p&gt;&amp;nbsp;&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;A lambda expression which uses 1 variable in a method where an existing lambda expression captures that same variable and another.&amp;nbsp; To maintain fidelity we would have to know about this and fake capture the second variable as well.&lt;/p&gt;   &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Now consider all of the problems above and consider the scenario where there are multiple threads and multiple instances of the current method active in the program.&amp;nbsp; How to determine which closure instance belongs to which thread, and just as important which stack frame on which thread, with respect to initializing values?&lt;/p&gt;  &lt;p&gt;None of the issues are an unsolvable problem but they do represent a significant cost to the feature.&amp;nbsp; And once again even if we added all of these features to the EE, ENC limitations would significantly limit the usefulness of the resulting feature.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Does this mean that LINQ, or any future metadata requiring expression, will never be added to the debugger window?&amp;nbsp; Absolutely not.&amp;nbsp; We’ve just hit the difficult stage of making compromises on the level of fidelity in the feature.&amp;nbsp; If you back off of true fidelity in a few small ways the resulting feature, while still very expensive, is significantly cheaper and removes many of the limitations imposed by ENC.&amp;nbsp;&amp;nbsp; This &lt;b&gt;hypothetical&lt;/b&gt; feature will be discussed in my next article.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;[1] For those interested the returned interface is &lt;a mce_href="http://msdn.microsoft.com/en-us/library/bb161287(VS.80).aspx" href="http://msdn.microsoft.com/en-us/library/bb161287(VS.80).aspx"&gt;IDebugProperty2&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;[2] Right now expressions are converted to a tree form slightly above IL and they are interpreted using the ICorDebug APIs.&amp;nbsp; Converting all the way down to IL requires a lot more work&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9877055" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx">Closures</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Debugging/default.aspx">Debugging</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Lambda/default.aspx">Lambda</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/LINQ/default.aspx">LINQ</category></item><item><title>Code Smell: Psychic classes</title><link>http://blogs.msdn.com/jaredpar/archive/2009/06/18/code-smell-psychic-classes.aspx</link><pubDate>Thu, 18 Jun 2009 17:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9771971</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9771971.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9771971</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9771971</wfw:comment><description>&lt;p&gt;Psychic classes have the appearance of ignoring data provided to it in an attempt to provide you with an answer they predict is better for the situation.&amp;#160;&amp;#160; It’s impossible to look at a the data provided to an instance of the class and understand what queries on the object will return because it may think of a better answer for you, or a better piece of data to look at.&lt;/p&gt;  &lt;p&gt;This comes from an example I ran into about a month ago.&amp;#160; I work on an IDE and naturally deal with a lot of parse trees and tokens.&amp;#160; Parsing everything all the time is expensive so naturally the results are cached in various places for performance reasons.&amp;#160; &lt;/p&gt;  &lt;p&gt;While debugging one such cache I noticed some strange behavior.&amp;#160; The cache wasn’t returning the right tree for the input it was provided.&amp;#160; So I decided to dig into the code a bit.&amp;#160; &lt;/p&gt;  &lt;p&gt;This cache takes several different forms of input which has no common base class or interface.&amp;#160; What I noticed though is that when resetting the input of the service, it would not clear the existing cache or the previous form of input.&amp;#160; Also because of the way the code loaded certain forms of input had precedence over others.&amp;#160; So even an explicit clear did not guarantee the “correct” input was used.&lt;/p&gt;  &lt;p&gt;The result is a service that reads well in code, but will not always act as you expect it to.&amp;#160; The service at times will seemingly ignore all input and pick a source it thinks is better.&amp;#160; Take the following code as an example&lt;/p&gt;  &lt;pre&gt;pCache-&amp;gt;SetSource(pSomeFile);
ParseTree* pTree = pCache-&amp;gt;GetTree();  &lt;/pre&gt;

&lt;p&gt;This code is very straight forward but is certainly not guaranteed to do what it appears to do. &lt;/p&gt;

&lt;p&gt;I like to think the service is predicting the results rather than calculating them.&amp;#160; Or better yet guessing the answer.&amp;#160; From the perspective of a code reviewer, that’s what’s happening.&amp;#160; &lt;/p&gt;

&lt;p&gt;Obviously I was curious about the reason for this and did a bit of research.&amp;#160; It’s a rather old class so I had to contact people who’d been on the team awhile back and dig through the history of the code base to understand what the purpose of this behavior was.&amp;#160; It turns out it was done to fix a few impactful scenarios where an alternate source needed precedence over the typical source.&amp;#160; Other devs didn’t fully understand the source semantics of the service and wrote methods that caused bad interactions.&amp;#160; Eventually it evolved to it’s current odd state.&amp;#160; &lt;/p&gt;

&lt;p&gt;Thanks to &lt;a href="http://diditwith.net/"&gt;Dustin&lt;/a&gt; for coining the term “psychic classes”.&amp;#160; Other ones we considered were&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Jedi Mind Trick classes: Weak name&lt;/li&gt;

  &lt;li&gt;Weatherman: It’s a prediction after all&amp;#160; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And yes, we fixed this issue :) &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9771971" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Humor/default.aspx">Humor</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Developing/default.aspx">Developing</category></item><item><title>Test-ItemProperty utility function</title><link>http://blogs.msdn.com/jaredpar/archive/2009/06/12/test-itemproperty-utility-function.aspx</link><pubDate>Fri, 12 Jun 2009 17:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9723349</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9723349.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9723349</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9723349</wfw:comment><description>&lt;p&gt;I was playing around in the registry the other day and found the PowerShell API lacking in a key area.&amp;#160; There does not appear to be a good way to detect the presence of a Registry Name/Value pair.&amp;#160; All of the operations such as New, Delete, Rename are based off of the program knowing the presence or absence of the key before hand.&amp;#160; This lacks symmetry with the rest of the APIs which have a test style function.&amp;#160; &lt;/p&gt;  &lt;pre&gt;PS&amp;gt; test-path &amp;quot;some\file\path\data.txt&amp;quot;
True&lt;/pre&gt;

&lt;p&gt;I took a few minutes and sketched out a basic Test-ItempProperty function.&amp;#160; It utilizes the Get-ItemProperty function and suppresses the rather loud red font error message via the –ErrorAction parameter (standard on all CmdLets).&amp;#160; &lt;/p&gt;

&lt;pre&gt;function Test-ItemProperty() {
    param ( [string]$path = $(throw &amp;quot;Need a path&amp;quot;),
            [string]$name = $(throw &amp;quot;Need a name&amp;quot;) )

    $temp = $null
    $temp = Get-ItemProperty -path $path -name $name -errorAction SilentlyContinue
    return $temp -ne $null
}&lt;/pre&gt;

&lt;p&gt;Now I can finish up my happy scripting for the night&lt;/p&gt;

&lt;pre&gt;PS&amp;gt; test-path . IsItScriptingTime
True&lt;/pre&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9723349" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/PowerShell/default.aspx">PowerShell</category></item><item><title>Can you @bing it?</title><link>http://blogs.msdn.com/jaredpar/archive/2009/05/28/can-you-bing-it.aspx</link><pubDate>Fri, 29 May 2009 03:21:33 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9651152</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9651152.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9651152</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9651152</wfw:comment><description>&lt;p&gt;Today Microsoft announced a new search engine called &lt;a href="http://www.bing.com/"&gt;bing&lt;/a&gt;.&amp;#160; I’ve been dogfooding this engine internally for some time now and from my experience it’s a step up from the previous engine in both functionality and appearance.&amp;#160; It’s definitely worth playing around with for awhile.&lt;/p&gt;  &lt;p&gt;Announcement: &lt;a href="http://www.microsoft.com/presspass/press/2009/may09/05-28NewSearchPR.mspx"&gt;http://www.microsoft.com/presspass/press/2009/may09/05-28NewSearchPR.mspx&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;While the functionality and accuracy of the results are certainly improved, this is not the biggest selling point for me.&amp;#160; I find Live Search’s results to be very good and noticeably improving over time.&amp;#160; I use it at home and work and rarely find a need to switch to google.com for anything.&amp;#160; But functionality isn’t everything.&lt;/p&gt;  &lt;p&gt;For me the biggest selling point is the new name.&amp;#160; Having a search engine with a 2 word name consisting of existing words prevented it from beating google in a key aspect of my life: the vernacular.&amp;#160; Google works great as a verb and hence allows itself to be injected into the conversation.&amp;#160; For instance “Can you google it real quick?”&amp;#160; &lt;/p&gt;  &lt;p&gt;What to do with live search though?&amp;#160; How can I express that I’m using live search without being too wordy?&amp;#160; “Can you live search it” just doesn’t have the same ring to it.&amp;#160; For awhile I shortened the name to learching (Live sEARCHING).&amp;#160; While that works, it doesn’t quite have a good ring to it.&amp;#160; &lt;/p&gt;  &lt;p&gt;Bing on the other hand works great&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Can you bing it?&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;You can view the engine at &lt;a href="http://www.bing.com"&gt;www.bing.com&lt;/a&gt; and the team is also twittering at &lt;a href="http://twitter.com/bing"&gt;@bing&lt;/a&gt;.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9651152" width="1" height="1"&gt;</description></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>Questions not to hinge a C++ interview on</title><link>http://blogs.msdn.com/jaredpar/archive/2009/04/21/questions-not-to-hinge-a-c-interview-on.aspx</link><pubDate>Tue, 21 Apr 2009 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9557943</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>7</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9557943.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9557943</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9557943</wfw:comment><description>&lt;p&gt;People love to chat about how to conduct a C++ interview on &lt;a href="http://stackoverflow.com/search?q=c%2B%2B+interview"&gt;newsgroups&lt;/a&gt;.&amp;#160; Eventually these topics will shift into a discussion about what questions a candidate &lt;strong&gt;must&lt;/strong&gt; know in order for them to get a hire from a particular interview.&amp;#160; Unfortunately these questions tend to be items like the following.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;What happens when you delete NULL?&lt;/li&gt;    &lt;li&gt;Explain how exceptions affect constructor initialization.&lt;/li&gt;    &lt;li&gt;Which constructors are called for the following: SomeType a = SomeType(b); &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Sure these questions are valid parts of the language and knowing them is a plus and demonstrates a deal of mastery over the language.&amp;#160; But not knowing them should by no means by a deal breaker.&amp;#160; The goal of an interview is to spot good developers who will become a contributing member of the team.&amp;#160; Good developers are motivated and passionate problem solvers.&amp;#160; These questions are testing little more than memorization.&amp;#160; It’s easy to memorize rules after the fact.&amp;#160; It’s much more difficult to teach problem solving skills.&amp;#160; &lt;/p&gt;  &lt;p&gt;The problem with questions like the above is that a developer could be both passionate and competent in C++ and never have come across these rules.&amp;#160; C++ is an unbelievably huge language and can operate in many different ways where these type of situations simply don’t come up.&amp;#160; For instance, I’ve known several very good C++ developers that spent the majority of their time working with COM.&amp;#160; COM prefers HRESULTs to Exceptions and hence they never used exceptions in C++.&amp;#160; Once we introduced exceptions into the code base, it took about 30 minutes to explain the rules and we were done.&amp;#160; &lt;/p&gt;  &lt;p&gt;C++ interviews should focus on the qualities that make a good developer: problem solving and passion.&amp;#160; Of course a language based interview should certainly focus on the foundations of C/C+.&amp;#160; Items like pointers, stack vs. heap and the basics of memory management.&amp;#160; But don’t hinge the deal on little items that can be quickly taught.&amp;#160; Otherwise you’ll end up turning away good developers.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9557943" 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/Rant/default.aspx">Rant</category></item><item><title>Immutable vs. Mutable Collection Performance</title><link>http://blogs.msdn.com/jaredpar/archive/2009/04/06/immutable-vs-mutable-collection-performance.aspx</link><pubDate>Mon, 06 Apr 2009 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9532916</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9532916.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9532916</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9532916</wfw:comment><description>&lt;p&gt;One argument I commonly hear against immutable collections is they are slow.&amp;#160; I’ve held the opposite belief for some time but shamefully had yet to look at actual numbers on the CLR.&amp;#160; Tonight I decided to change that by benchmarking one of &lt;a href="http://code.msdn.com/BclExtras"&gt;my immutable collections&lt;/a&gt; against a mutable collection in the BCL.&amp;#160; The goal is not to decide the overall best collection but instead to get a sense of how they perform relative to each other in certain scenarios.&lt;/p&gt;  &lt;p&gt;For the immutable version, I chose to use ImmutableCollection.&amp;#160; This class is a slight variation of Eric Lippert’s &lt;a href="http://blogs.msdn.com/ericlippert/archive/2008/02/12/immutability-in-c-part-eleven-a-working-double-ended-queue.aspx"&gt;Double Ended Queue&lt;/a&gt; implementation.&amp;#160; The core algorithm is the same but the style was changed to be more inline with other immutable collections I own. For the mutable class I chose to use the ever popular &lt;a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx"&gt;List&amp;lt;T&amp;gt;&lt;/a&gt; collection.&amp;#160; &lt;/p&gt;  &lt;p&gt;I chose to examine the following scenarios that I commonly use with collection style classes.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Adding to the end of the collection &lt;/li&gt;    &lt;li&gt;Adding to the front of the collection &lt;/li&gt;    &lt;li&gt;Removing from the end of the collection &lt;/li&gt;    &lt;li&gt;Removing from the beginning of the collection &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Each scenario was run against collections of 100, 1000 and 10000 elements.&amp;#160; For each count, the run was executed 1000 times and the total and average time was calculated.&amp;#160; The full code for the benchmark is available at the end of this post.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Looking at the data&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Now before I get into the results, please assume the usual caveats that come with any benchmark.&amp;#160; That is, approach it with a skeptical eye.&amp;#160; These scenarios are obviously not something I do &lt;strong&gt;exactly &lt;/strong&gt;in everyday programming (especially removing thousands of elements from the front of List&amp;lt;T&amp;gt;).&amp;#160; However they are representative of general operations that I do use.&amp;#160; Also I find it interesting to see how the collections perform relative to each other in extreme scenarios.&lt;/p&gt;  &lt;p&gt;Most of the results were unsurprising.&amp;#160; Remove from end is a very simple operation on a List&amp;lt;T&amp;gt;.&amp;#160; It comes down to a bounds check, decrementing an index and updating a couple of internal state variables.&amp;#160;&amp;#160; Removing the end of an immutable collection requires considerable updating of the internal structure.&amp;#160; It ends up being roughly 1 order of magnitude slower.&amp;#160;&amp;#160;&amp;#160; Adding to the end has similar implementation and numbers.&lt;/p&gt;  &lt;p&gt;Operations on the front of the list were significantly slower on List&amp;lt;T&amp;gt; than ImmutableCollection for suitably large collections.&amp;#160; This is unsurprising given that removal and insertion at the front of a List&amp;lt;T&amp;gt; requires all of the other elements in the underlying array to be shifted up or down.&amp;#160; This is a non-trivial operation and is evident in the benchmark.&amp;#160; &lt;/p&gt;  &lt;p&gt;The most interesting item however, is to look at how each collection scales.&amp;#160; In almost all scenarios, ImmutableCollection scaled very closely to the size of the input.&amp;#160; That is, an order of magnitude more input resulted in an order of magnitude of more time.&amp;#160; List&amp;lt;T&amp;gt; does not have that behavior for all scenarios.&amp;#160; Scenarios dealing with the front of the collection saw time rises faster relative to input size.&amp;#160; In fact there is a very dramatic jump in both front scenarios between 1000 and 1000 elements.&amp;#160; Each case resulted in roughly 2 orders of magnitude more time.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Winner of each category … &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Add to End: List&amp;lt;T&amp;gt; &lt;/li&gt;    &lt;li&gt;Add to Front: ImmutableCollection&amp;lt;T&amp;gt; &lt;/li&gt;    &lt;li&gt;Remove from End: List&amp;lt;T&amp;gt; &lt;/li&gt;    &lt;li&gt;Remove from Front: ImmutableCollection&amp;lt;T&amp;gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;No single benchmark is definitive and this one won’t change that.&amp;#160; This benchmark says nothing about the general use of the two classes.&amp;#160; However it can provide some insight into these specific scenarios.&amp;#160; It also serves as some level of proof that immutable collections can have acceptable performance for these scenarios.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Data&lt;/strong&gt;&lt;/p&gt;  &lt;pre&gt;Add to End 100 Elements
       List: Total: 00:00:00.0060473 Average: 00:00:00.0000060
  Immutable: Total: 00:00:00.0267079 Average: 00:00:00.0000267
Add to End 1000 Elements
       List: Total: 00:00:00.0337505 Average: 00:00:00.0000337
  Immutable: Total: 00:00:00.2240444 Average: 00:00:00.0002240
Add to End 10000 Elements
       List: Total: 00:00:00.4266014 Average: 00:00:00.0004266
  Immutable: Total: 00:00:02.6715789 Average: 00:00:00.0026715
Add to Front 100 Elements
       List: Total: 00:00:00.0162186 Average: 00:00:00.0000162
  Immutable: Total: 00:00:00.0213764 Average: 00:00:00.0000213
Add to Front 1000 Elements
       List: Total: 00:00:00.4028523 Average: 00:00:00.0004028
  Immutable: Total: 00:00:00.2055935 Average: 00:00:00.0002055
Add to Front 10000 Elements
       List: Total: 00:00:38.5943722 Average: 00:00:00.0385943
  Immutable: Total: 00:00:02.6212590 Average: 00:00:00.0026212
Remove From End 100 Elements
       List: Total: 00:00:00.0031299 Average: 00:00:00.0000031
  Immutable: Total: 00:00:00.0213737 Average: 00:00:00.0000213
Remove From End 1000 Elements
       List: Total: 00:00:00.0187998 Average: 00:00:00.0000187
  Immutable: Total: 00:00:00.1623739 Average: 00:00:00.0001623
Remove From End 10000 Elements
       List: Total: 00:00:00.1773381 Average: 00:00:00.0001773
  Immutable: Total: 00:00:01.9615781 Average: 00:00:00.0019615
Remove From Front 100 Elements
       List: Total: 00:00:00.0142981 Average: 00:00:00.0000142
  Immutable: Total: 00:00:00.0192679 Average: 00:00:00.0000192
Remove From Front 1000 Elements
       List: Total: 00:00:00.4407993 Average: 00:00:00.0004407
  Immutable: Total: 00:00:00.1879243 Average: 00:00:00.0001879
Remove From Front 10000 Elements
       List: Total: 00:00:39.7832085 Average: 00:00:00.0397832
  Immutable: Total: 00:00:02.2451406 Average: 00:00:00.0022451&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;The Code&lt;/strong&gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Program &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ImmutableCollectionAddToEnd(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; list) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;col = &lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;.Empty;
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;item &lt;span style="color: blue"&gt;in &lt;/span&gt;list) {
            col = col.AddBack(item);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ListAddToEnd(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; list) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;col = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;();
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;item &lt;span style="color: blue"&gt;in &lt;/span&gt;list) {
            col.Add(item);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;RunAddToEnd(&lt;span style="color: blue"&gt;int &lt;/span&gt;count) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;list = &lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(0, count).Select(x =&amp;gt; x.ToString()).ToList();
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Add to End {0} Elements&amp;quot;&lt;/span&gt;, count);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;List&amp;quot;&lt;/span&gt;, ListAddToEnd, () =&amp;gt; list);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;Immutable&amp;quot;&lt;/span&gt;, ImmutableCollectionAddToEnd, () =&amp;gt; list);
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ImmutableCollectionAddToFront(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; list) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;col = &lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;.Empty;
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;item &lt;span style="color: blue"&gt;in &lt;/span&gt;list) {
            col = col.AddFront(item);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ListAddToFront(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; list) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;col = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;();
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;item &lt;span style="color: blue"&gt;in &lt;/span&gt;list) {
            col.Insert(0, item);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;RunAddToFront(&lt;span style="color: blue"&gt;int &lt;/span&gt;count) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;list = &lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(0, count).Select(x =&amp;gt; x.ToString()).ToList();
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Add to Front {0} Elements&amp;quot;&lt;/span&gt;, count);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;List&amp;quot;&lt;/span&gt;, ListAddToFront, () =&amp;gt; list);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;Immutable&amp;quot;&lt;/span&gt;, ImmutableCollectionAddToFront, () =&amp;gt; list);
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ImmutableCollectionRemoveFromEnd(&lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; col) {
        &lt;span style="color: blue"&gt;while &lt;/span&gt;(!col.IsEmpty) {
            col = col.RemoveBack();
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ListRemoveFromEnd(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; list) {
        &lt;span style="color: blue"&gt;while &lt;/span&gt;(list.Count &amp;gt; 0) {
            list.RemoveAt(list.Count - 1);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;RunRemoveFromEnd(&lt;span style="color: blue"&gt;int &lt;/span&gt;count) {
        &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; listInputFunc = () =&amp;gt; &lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(0, count).Select(x =&amp;gt; x.ToString()).ToList();
        &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; colInputFunc = () =&amp;gt; &lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;.Create(listInputFunc());
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Remove From End {0} Elements&amp;quot;&lt;/span&gt;, count);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;List&amp;quot;&lt;/span&gt;, ListRemoveFromEnd, listInputFunc);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;Immutable&amp;quot;&lt;/span&gt;, ImmutableCollectionRemoveFromEnd, colInputFunc);
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ImmutableCollectionRemoveFromFront(&lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; col) {
        &lt;span style="color: blue"&gt;while &lt;/span&gt;(!col.IsEmpty) {
            col = col.RemoveFront();
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;ListRemoveFromFront(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; col) {
        &lt;span style="color: blue"&gt;while &lt;/span&gt;(col.Count &amp;gt; 0) {
            col.RemoveAt(0);
        }
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;RunRemoveFromFront(&lt;span style="color: blue"&gt;int &lt;/span&gt;count) {
        &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; listInputFunc = () =&amp;gt; &lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(0, count).Select(x =&amp;gt; x.ToString()).ToList();
        &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; colInputFunc = () =&amp;gt; &lt;span style="color: #2b91af"&gt;ImmutableCollection&lt;/span&gt;.Create(listInputFunc());
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Remove From Front {0} Elements&amp;quot;&lt;/span&gt;, count);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;List&amp;quot;&lt;/span&gt;, ListRemoveFromFront, listInputFunc);
        RunScenario(&lt;span style="color: #a31515"&gt;&amp;quot;Immutable&amp;quot;&lt;/span&gt;, ImmutableCollectionRemoveFromFront, colInputFunc);
    }
    &lt;span style="color: blue"&gt;public static void &lt;/span&gt;RunScenario&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;string &lt;/span&gt;description, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt; del, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt; getInputFunc) {
        &lt;span style="color: green"&gt;// Run once to jit
        &lt;/span&gt;del(getInputFunc());
        &lt;span style="color: blue"&gt;const int &lt;/span&gt;times = 1000;
        &lt;span style="color: blue"&gt;var &lt;/span&gt;total = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt;();
        &lt;span style="color: blue"&gt;for &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;i = 0; i &amp;lt; times; i++) {
            &lt;span style="color: green"&gt;// get the input outside the timer so input creation is not calculated 
            &lt;/span&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;input = getInputFunc();
            &lt;span style="color: blue"&gt;var &lt;/span&gt;watch = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Stopwatch&lt;/span&gt;();
            watch.Start();
            del(input);
            watch.Stop();
            total += watch.Elapsed;
        }
        &lt;span style="color: blue"&gt;var &lt;/span&gt;average = &lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt;.FromTicks(total.Ticks / times);
        &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0,11}: Total: {1} Average: {2}&amp;quot;&lt;/span&gt;, description, total, average);
    }
    &lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;list = &lt;span style="color: blue"&gt;new int&lt;/span&gt;[] { 100, 1000, 10000 };
        list.ForEach(RunAddToEnd);
        list.ForEach(RunAddToFront);
        list.ForEach(RunRemoveFromEnd);
        list.ForEach(RunRemoveFromFront);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9532916" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Performance/default.aspx">Performance</category></item><item><title>Is it Serializable?</title><link>http://blogs.msdn.com/jaredpar/archive/2009/03/31/is-it-serializable.aspx</link><pubDate>Tue, 31 Mar 2009 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9499985</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9499985.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9499985</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9499985</wfw:comment><description>&lt;p&gt;I’ve recently run across several APIs that have a dependency on only dealing with objects that are serializable (in the binary sense).&amp;#160; Unfortunately determining if an object is serializable is a non-trivial task and rife with problems.&amp;#160; These problems have a direct impact on the types of guarantees these APIs can make.&lt;/p&gt;  &lt;p&gt;For all objects which are serializable, it’s only possible to prove that a very small subset of them actually are in code.&amp;#160; Easier but less reliable tests are very easy to write.&amp;#160; So APIs must make a trade off.&amp;#160; Only accept instances of types which are provable serializable and miss out on a while class of objects.&amp;#160; Or do a much less reliable check and open themselves up to failure further down in the algorithm.&lt;/p&gt;  &lt;p&gt;Take System.Exception for example.&amp;#160; It is possible to associate arbitrary data with an exception through the &lt;a href="http://msdn.microsoft.com/en-us/library/system.exception.data.aspx"&gt;Data&lt;/a&gt; property.&amp;#160; Associated just any object with Exception is problematic though because Exceptions &lt;a href="http://winterdom.com/weblog/2007/01/16/MakeExceptionClassesSerializable.aspx"&gt;should be serializable&lt;/a&gt;.&amp;#160; In order for an Exception instance to store these objects and remain serializable, the objects must also be serializable.&amp;#160; Since serializability is not provable, the authors of Exception had to make a trade off between an overly restrictive test, or a loose test.&amp;#160; They chose the latter.&amp;#160; As a result it’s impossible to determine before hand if a given Exception instance is actually serializable.&amp;#160; &lt;/p&gt;  &lt;p&gt;Why is this the case though that serialization is tough to determine?&amp;#160; Lets start with what it takes to make a type serializable.&amp;#160; There are two separate components&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Declaring that the type is Serializable by either having the SerializableAttribute on the class definition or by implementing ISerializable &lt;/li&gt;    &lt;li&gt;Making the type conform to the rules of serialization.&amp;#160; &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;These are completely separate actions.&amp;#160; It’s possible to have types which do any combination of the above but not both.&amp;#160; Take for instance the following type declarations&lt;/p&gt;  &lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Serializable&lt;/span&gt;]
&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;DeclaredOnly &lt;/span&gt;{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ConformsOnly &lt;/span&gt;m_conforms;
}

&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ConformsOnly &lt;/span&gt;{
    &lt;span style="color: blue"&gt;private string &lt;/span&gt;m_name;
}&lt;/pre&gt;

&lt;p&gt;Both of these types are legal C# code and both represent one of the two extremes listed above.&amp;#160; Yet neither of these types are actually serializable.&amp;#160; ConformsOnly is not because it has not actually declared itself to be serializable.&amp;#160; DeclaredOnly is not because one of it’s members is not serializable.&amp;#160; &lt;/p&gt;

&lt;p&gt;Lets look at proving serialization by ensuring types follow both of the rules.&amp;#160; Proving the first part of serialization is pretty straight forward.&amp;#160; Simply check to see if a type implements ISerializable or is decorated with the Serialization attribute.&amp;#160; The latter is directly supported in the type system via &lt;a href="http://msdn.microsoft.com/en-us/library/system.type.isserializable.aspx"&gt;Type.IsSerializable&lt;/a&gt;.&amp;#160; This property is also the source of the most common mistake I see with respect to determining if an object is serializable.&amp;#160; Take the following code snippet for an example.&lt;/p&gt;

&lt;p&gt;&lt;span style="color: blue"&gt;public static void&lt;/span&gt;Example1(&lt;span style="color: blue"&gt;object &lt;/span&gt;o) { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color: blue"&gt;if&lt;/span&gt;(o.GetType().IsSerializable) { 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color: green"&gt;// Do something different 
    &lt;br /&gt;&amp;#160;&amp;#160; &lt;/span&gt;} 

  &lt;br /&gt;}&lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;On the surface, this looks like reasonable code.&amp;#160; But as we just pointed out, the property IsSerializable just determines the presence or absence of the Serializable attribute but nothing about the second part.&amp;#160; A more descriptive attribute name would be IsSerializableAttributeDeclared.&amp;#160; Yet many pieces of code attempt to equate this property with the ability to be serialized (A fun experiment here is to search for it’s use in Reflector)&lt;/p&gt;

&lt;p&gt;Proving the second part involves two cases, types implementing ISerializable and types decorated with the Serializable attribute.&amp;#160; Lets start with the attribute.&amp;#160; Proving these is involved but a straight forward process.&amp;#160; The type must …&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Be decorated with the Serializable Attribute &lt;/li&gt;

  &lt;li&gt;One of the following items must be true for every field at all points in the hierarchy 
    &lt;ol&gt;
      &lt;li&gt;It must be decorated with the NonSerializedAttribute &lt;/li&gt;

      &lt;li&gt;The type of the field must be sealed and must conform to all of these rules &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Instances of types which meet these guidelines will always be serializable.&amp;#160; Not meeting these rules though does not exclude a type from serialization.&amp;#160; There are several sets of types decorated with Serializable which are serializable and do not meet these rules. &lt;/p&gt;

&lt;p&gt;Take for instance types that violate rule 2.2.&amp;#160; By having a field whose type is not sealed, it is possible to construct a runtime instance which contains a value whose type is not serializable.&amp;#160; The following type fits into this category.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Serializable&lt;/span&gt;]
&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;OnlyKnownPerInstance &lt;/span&gt;{
    &lt;span style="color: blue"&gt;private object &lt;/span&gt;m_field1;
}&lt;/pre&gt;

&lt;p&gt;Whether or not an instance of this type is serializable depends on the value of m_field1.&amp;#160; So the only way to prove it is serializable is to look at the runtime information.&amp;#160; This makes any definitive analysis on the type impossible.&amp;#160; The actual object must be inspected.&lt;/p&gt;

&lt;p&gt;The other case to examine are types implementing ISerializable.&amp;#160; Serialization is a custom task for instances of these types and is done in imperative code.&amp;#160; Proving these types are serializable involves actual algorithm inspection and is beyond the scope of this blog post.&amp;#160; But suffice to say, proving these are serializable is an order of magnitude more difficult. &lt;/p&gt;

&lt;p&gt;Getting back to the crux of this article.&amp;#160; What is the best way to determine if an object is serializable or not?&amp;#160; Bottom line, there is no good way.&amp;#160; The only 100% definitive way is to serialize the object and see if it succeeds or not.&amp;#160; This is problematic because it is not future proof.&amp;#160; It only tells you that the object &lt;strong&gt;was &lt;/strong&gt;serializable.&amp;#160; This is a very important distinction.&amp;#160; It’s possible for the object to be mutated in a different state later on which will prevent it from being properly serializable.&amp;#160; &lt;/p&gt;

&lt;p&gt;If serialization of a parameter is very important to the semantics of an API this is the only way to ensure the semantics are not violated is to serialize the object immediately and store the binary data.&amp;#160; Otherwise you can only make a loose guarantee that an attempt to serialize in the future will succeed.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9499985" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>Building a WeakReference Hashtable</title><link>http://blogs.msdn.com/jaredpar/archive/2009/03/03/building-a-weakreference-hashtable.aspx</link><pubDate>Tue, 03 Mar 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9389341</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9389341.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9389341</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9389341</wfw:comment><description>&lt;p&gt;Recently I ran into a situation on a personal project where I needed a hashtable like structure for a set of WeakReference values.&amp;#160; When poking around for an existing implementation I saw found several versions which were very thin, type safe wrapper around a Dictionary&amp;lt;TKey,WeakReference&amp;gt; (usually the class even implements IDictionary&amp;lt;TKey,TValue&amp;gt; directly).&amp;#160; While this produces a type safe API it fails to take into account the different nature of a WeakReference.&amp;#160; Because a WeakReference is constantly being collected without explicit user action it alters the types of operations that be performed on them.&amp;#160; Failing to take this into account produced APIs which lead users to write incorrect code.&lt;/p&gt;  &lt;p&gt;Finding no suitable implementation I set off to build my own.&amp;#160; It took several iterations and I thought the result and process would be fun to share the design experience as a blog post.&amp;#160; &lt;/p&gt;  &lt;p&gt;Let start with the basics.&amp;#160; At a high level the API should appear to the user as a type safe Dictionary&amp;lt;TKey,TValue&amp;gt;.&amp;#160; Under the hood all values will be stored in an instance of WeakReference in order to enable collection.&amp;#160; But this is an implementation detail and should not be visible to the user.&amp;#160;&amp;#160; The user should only see type safe keys and values.&lt;/p&gt;  &lt;p&gt;A standard Hashtable works on the concept of a key/value pair.&amp;#160; A value is associated with a particular key in the table and at any time, the value can be retrieved from the hashtable with the specified key.&amp;#160; A key can be determined to be valid simply by ascertaining it’s presence in the underlying table.&amp;#160; The value is irrelevant, it’s mere presence makes it valid. &lt;/p&gt;  &lt;p&gt;A weak hashtable will work on the same concept but have a much different implementation.&amp;#160; Keys are only valid if they point to an actual value.&amp;#160; Since the value in the hashtable is a WeakReference the mere presence of the key does not determine it’s validity.&amp;#160; Only the presence of the key and the value contained within the weak reference determines the validity of a key.&amp;#160; &lt;/p&gt;  &lt;p&gt;This seems like an obvious assumption but it has a dramatic impact on the type of API a weak hashtable can have.&amp;#160; Lets take a simple property such as Count for an example of why this is important.&amp;#160; Count on a hashtable is used to determine the number of valid key/value pairs in the table.&amp;#160; On a normal hashtable, this count is simply incremented and decremented with the corresponding Add and Remove API’s.&amp;#160; With a weak hashtable, any given run of the garbage collector can affect the count of key/value pairs by collecting a value.&amp;#160; This means a simple counter cannot be used to keep track of the valid key/value pairs.&amp;#160; &lt;/p&gt;  &lt;p&gt;In order to get the actual Count every singe value must be accessed an verified that it is still alive.&amp;#160; What’s even worse is that once a value is determined to exist, it must be stored for the duration of the Count method.&amp;#160; Otherwise a GC could occur in the middle of the loop and collect Values that were marked as still alive.&amp;#160; &lt;/p&gt;  &lt;p&gt;This is what Count would need to look like …&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WeakHashtable&lt;/span&gt;&amp;lt;TKey,TValue&amp;gt; {
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;TKey, &lt;span style="color: #2b91af"&gt;WeakReference&lt;/span&gt;&amp;gt; _map;
    &lt;span style="color: blue"&gt;public int &lt;/span&gt;Count {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{
            &lt;span style="color: blue"&gt;var &lt;/span&gt;list = _map.Values
                .Select(x =&amp;gt; x.Target)
                .Where(x =&amp;gt; x != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
                .ToList();
            &lt;span style="color: blue"&gt;return &lt;/span&gt;list.Count;
        }
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Count transformed from a simple O(1) return of an internal counter to a O(N) method which allocates memory.&amp;#160; Worse yet, the return value is practically useless.&amp;#160; As soon as the value is returned it cannot be considered to be valid.&amp;#160; A GC could kick in and invalidate half the table.&amp;#160; Count would in fact be giving the user information about the object in the past.&amp;#160; &lt;/p&gt;

&lt;p&gt;In some ways, this problem is similar to issues encountered with multi-threaded applications.&amp;#160; In between every line of your code there is another operation, in this case the GC, which can alter the state of your structure.&amp;#160; &lt;/p&gt;

&lt;p&gt;The only API’s that can ask questions about a value and still have a reasonable use by the user must return the value with the call.&amp;#160; Returning the value will, at least temporarily, provide a GC root and prevent the object from being collected.&amp;#160; It gives the user a chance to use the value before it’s taken out from under them. &lt;/p&gt;

&lt;p&gt;A good API comparison here are operations such as Contains and TryGetValue.&amp;#160; Contains holds no value to the user because as soon as the call returns the GC can collect the value.&amp;#160; TryGetValue on the other hand returns the value in question thus locking it in memory and preventing a collection.&amp;#160; &lt;/p&gt;

&lt;p&gt;When designing the API for a weak hashtable I tried to keep it simple and stick to these ideas.&amp;#160; I started with the &lt;a href="http://msdn.microsoft.com/en-us/library/s4ys34ea.aspx"&gt;IDictionary&amp;lt;TKey,TValue&amp;gt;&lt;/a&gt; interface and removed the methods which hold no value for the end user due to GC limitations.&amp;#160; In the end I was left with only the following.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;void Add(TKey key, TValue value) &lt;/li&gt;

  &lt;li&gt;bool Remove(TKey key) &lt;/li&gt;

  &lt;li&gt;void Clear() &lt;/li&gt;

  &lt;li&gt;bool TryGetValue(TKey key, out TValue value) &lt;/li&gt;

  &lt;li&gt;List&amp;lt;TValue&amp;gt; Values { get; } &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I also added the following methods&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;List&amp;lt;Tuple&amp;lt;TKey,TValue&amp;gt;&amp;gt; Pairs&amp;#160; { get; } &lt;/li&gt;

  &lt;li&gt;Put(TKey key, TValue value) &lt;/li&gt;

  &lt;li&gt;Option&amp;lt;TValue&amp;gt; TryGetValue(TKey key); &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Values property returns a List&amp;lt;TValue&amp;gt; implementation instead of IEnumerable&amp;lt;TValue&amp;gt;&amp;#160; In order to guarantee the values remain in existence they must be rooted in some structure.&amp;#160; The easy choice is a List&amp;lt;TValue&amp;gt;.&amp;#160; Since a List&amp;lt;TValue&amp;gt; must be created anyways, why return a less accessible interface such as IEnumerable&amp;lt;TValue&amp;gt;?&amp;#160; &lt;/p&gt;

&lt;p&gt;At first I did consider a design where Values returned IEnumerable.&amp;#160; It is fairly simple to implement with a C# iterator.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;TValue&amp;gt; Values {
    &lt;span style="color: blue"&gt;get &lt;/span&gt;{
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;weakRef &lt;span style="color: blue"&gt;in &lt;/span&gt;_map.Values) {
            &lt;span style="color: blue"&gt;var &lt;/span&gt;obj = weakRef.Target;
            &lt;span style="color: blue"&gt;if &lt;/span&gt;(obj != &lt;span style="color: blue"&gt;null&lt;/span&gt;) {
                &lt;span style="color: blue"&gt;yield return &lt;/span&gt;(TValue)obj;
            }
        }
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The problem though is that anything more than a simple .ForEach() over the IEnumerable may behave unexpectedly.&amp;#160; Consecutive calls to GetEnumerator can produce different enumerations with no explicit user alteration of the table.&amp;#160; I’ve seen several APIs which (rightly or wrongly) make this assumption.&amp;#160; Given the user is not explicitly modifying the collection, it is not a necessarily bad assumption to make.&amp;#160; However it would not work for a collection of this type.&lt;/p&gt;

&lt;p&gt;I intentionally left off Keys here.&amp;#160; Keys are only valid when they have a live value in the table.&amp;#160; Unless the Value is returned with Key this cannot be guaranteed.&amp;#160; The Pairs property serves this role.&amp;#160; &lt;/p&gt;

&lt;p&gt;This post went a bit longer than I originally intended.&amp;#160; I also wanted to discuss how compaction of the table should work in a weak hashtable.&amp;#160; I’ll save that for next time.&amp;#160; &lt;/p&gt;

&lt;p&gt;Here is the implementation of the dictionary without any compaction support.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public sealed class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WeakDictionary&lt;/span&gt;&amp;lt;TKey, TValue&amp;gt; {
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;TKey, &lt;span style="color: #2b91af"&gt;WeakReference&lt;/span&gt;&amp;gt; m_map;

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;&amp;lt;TKey, TValue&amp;gt;&amp;gt; Pairs {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{
            &lt;span style="color: blue"&gt;return &lt;/span&gt;m_map
                    .Select(p =&amp;gt; &lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;.Create(p.Key, p.Value.Target))
                    .Where(t =&amp;gt; t.Second != &lt;span style="color: blue"&gt;null&lt;/span&gt;)
                    .Select(t =&amp;gt; &lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;.Create(t.First, (TValue)t.Second))
                    .ToList();
        }
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;TValue&amp;gt; Values {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;Pairs.Select(x =&amp;gt; x.Second).ToList(); }
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;WeakDictionary()
        : &lt;span style="color: blue"&gt;this&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;EqualityComparer&lt;/span&gt;&amp;lt;TKey&amp;gt;.Default) {
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;WeakDictionary(&lt;span style="color: #2b91af"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;TKey&amp;gt; comparer) {
        m_map = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;TKey, &lt;span style="color: #2b91af"&gt;WeakReference&lt;/span&gt;&amp;gt;(comparer);
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Add(TKey key, TValue value) {
        m_map.Add(key, &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WeakReference&lt;/span&gt;(value));
    }

    &lt;span style="color: blue"&gt;public void &lt;/span&gt;Put(TKey key, TValue value) {
        m_map[key] = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;WeakReference&lt;/span&gt;(value);
    }

    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;Remove(TKey key) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;m_map.Remove(key);
    }

    &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;TValue&amp;gt; TryGetValue(TKey key) {
        &lt;span style="color: #2b91af"&gt;WeakReference &lt;/span&gt;weakRef;
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(!m_map.TryGetValue(key, &lt;span style="color: blue"&gt;out &lt;/span&gt;weakRef)) {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;.Empty;
        }

        &lt;span style="color: blue"&gt;var &lt;/span&gt;target = weakRef.Target;
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(target == &lt;span style="color: blue"&gt;null&lt;/span&gt;) {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;.Empty;
        }

        &lt;span style="color: blue"&gt;return &lt;/span&gt;(TValue)target;
    }

    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;TryGetValue(TKey key, &lt;span style="color: blue"&gt;out &lt;/span&gt;TValue value) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;option = TryGetValue(key);
        value = option.ValueOrDefault;
        &lt;span style="color: blue"&gt;return &lt;/span&gt;option.HasValue;
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9389341" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>A more usable API for a mutable thread safe collection</title><link>http://blogs.msdn.com/jaredpar/archive/2009/02/16/a-more-usable-thread-safe-collection.aspx</link><pubDate>Mon, 16 Feb 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9424930</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>17</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9424930.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9424930</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9424930</wfw:comment><description>
&lt;p&gt;In my last &lt;a href="http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx" mce_href="http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx"&gt;post&lt;/a&gt; we discussed the problems with designing a safer API for mutable thread safe collections that employ only an internal locking system.&amp;nbsp; The result was an API that was more difficult to mess up, yet pretty much unusable.&amp;nbsp; Lets take a look at this problem and see if we can come up with a usable API that still helps to eliminate mistakes.&amp;nbsp; &lt;/p&gt;
  
&lt;p&gt;One of the main issues I have with mutable thread safe collections is the use of decision procedures such as Count and Contains.&amp;nbsp; Procedures such these only return information that pertains to the collection as it existed at a previous point in time.&amp;nbsp; It can provide no relevant information to the collection in it’s current state and only encourages the user to write bad code.&amp;nbsp; For example.&amp;nbsp; &lt;/p&gt;
  
&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;if &lt;/span&gt;(col.Count &amp;gt; 0) {&lt;br&gt;    &lt;span style="color: green;"&gt;// Collection can be modified before this next line executes leading to &lt;br&gt;    // an error condition&lt;br&gt;    &lt;/span&gt;&lt;span style="color: blue;"&gt;var &lt;/span&gt;first = col[0]; &lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Therefore they have no place on a mutable thread safe collection.&amp;nbsp; Yet, once you take away these procedures, you’re left with a collection that is virtually useless.&amp;nbsp; It can only have a minimal API by which to access data.&amp;nbsp; Here is the last example we were left with &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeList&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Add(T value) { ... }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;TryRemove(T value) { ... }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;TryGet(&lt;span style="color: blue;"&gt;int &lt;/span&gt;index, &lt;span style="color: blue;"&gt;out &lt;/span&gt;T value) { ... }&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This is hardly a usable API.&amp;nbsp; What’s worse, as wekempf point out, is that I inadvertently exposed a decision procedure in this API.&amp;nbsp; It’s possible to infer state about a lower or equal index by a successful return result from TryGet().&amp;nbsp; For example, a user may say that “if I can access element 2, then surely element 1 must exist”.&amp;nbsp; The result would still be evident in code (ignoring the return value of a TryGet method should be a red flag).&amp;nbsp; But a better choice for this method would have been a TryGetFirst().&amp;nbsp; &lt;/p&gt;

&lt;p&gt;At the end of the day, users are going to want some level of determinism out of their collections.&amp;nbsp; It’s possible to program against API’s like the above, but most people won’t do it.&amp;nbsp; In order to be more used, the collection must be able to reliably implement procedures such as Count and Contains and allow the user to use the return to reason about the state of the collection.&lt;/p&gt;

&lt;p&gt;One way to do this is to simply exposed the internal lock to the consumer of the collection.&amp;nbsp; Consumers can take the lock and then query to their hearts content.&amp;nbsp; Lets do a quick modification of the original sample to allow for this.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeList&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;    &lt;span style="color: blue;"&gt;private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt; m_list = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;List&lt;/span&gt;&amp;lt;T&amp;gt;();&lt;br&gt;    &lt;span style="color: blue;"&gt;private object &lt;/span&gt;m_lock = &lt;span style="color: blue;"&gt;new object&lt;/span&gt;();&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public object &lt;/span&gt;SyncLock { &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_lock; } }&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Add(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_list.Add(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Remove(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_list.Remove(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;Contains(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list.Contains(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;    &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Count { &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list.Count; } } }&lt;br&gt;    &lt;span style="color: blue;"&gt;public &lt;/span&gt;T &lt;span style="color: blue;"&gt;this&lt;/span&gt;[&lt;span style="color: blue;"&gt;int &lt;/span&gt;index] {&lt;br&gt;        &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_list[index]; } }&lt;br&gt;        &lt;span style="color: blue;"&gt;set &lt;/span&gt;{ &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) { m_list[index] = &lt;span style="color: blue;"&gt;value&lt;/span&gt;; } }&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now we can go back to the original sample code and write a version which can use the decision procedures safely.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;lock &lt;/span&gt;(col.SyncLock) {&lt;br&gt;    &lt;span style="color: blue;"&gt;if &lt;/span&gt;(col.Count &amp;gt; 0) {&lt;br&gt;        &lt;span style="color: blue;"&gt;var &lt;/span&gt;first = col[0];&lt;br&gt;        ...&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This code will function correctly.&amp;nbsp; But the API leaves a lot to be desired.&amp;nbsp; In particular … &lt;/p&gt;

&lt;ol&gt;
  
&lt;li&gt;It provides no guidance to the user as to which procedures must be accessed with the SyncLock object locked.&amp;nbsp; They can just as easily write the original bad sample code.&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;
    
&lt;p&gt;All procedures used within the lock reacquire the lock recursively which is definitely &lt;a href="http://zaval.org/resources/library/butenhof1.html" mce_href="http://zaval.org/resources/library/butenhof1.html"&gt;not advisable&lt;/a&gt;.&amp;nbsp; We could provide properties which do not acquire the lock such as CountNoLock that work around this problem. While ok in small doses, it's just a matter of time before you see this snippet in the middle of a huge mostly undocumented function&lt;/p&gt;

    
&lt;pre class="code"&gt;&lt;span style="color: green;"&gt;// Lock should be held at this point&lt;br&gt;&lt;/span&gt;&lt;span style="color: blue;"&gt;int &lt;/span&gt;count = col.CountNoLock;&lt;/pre&gt;
    &lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
    
&lt;p&gt;This code makes my eyes bleed&lt;/p&gt;
  &lt;/li&gt;

  
&lt;li&gt;The API provides 0 information to the user on exactly what the rules are for this lock.&amp;nbsp; It would be left as an artifact in documentation (which you simply cannot count on users reading).&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;There is really nothing telling the user that they ever have to unlock the collection.&amp;nbsp; Surely, any user entering into the world of threading should know this but if they do a Monitor.Enter call without a corresponding Monitor.Exit, they will receive no indication this is a bad idea.&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;Overall this collection requires a lot of new knowledge about the collection to use &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This design though is exactly how a “synchronized” collection in 1.0 version of the BCL worked.&amp;nbsp; This code is essentially what you would get by passing an ArrayList instance to ArrayList.Synchronized (and most other BCL 1.0 collections).&amp;nbsp;&amp;nbsp; It was problematic enough that all of the new collections in 2.0 did not implement this &lt;i&gt;feature&lt;/i&gt;.&amp;nbsp; Here’s the BCL team’s explanation on this &lt;a href="http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx" title="http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx" mce_href="http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx"&gt;http://blogs.msdn.com/bclteam/archive/2005/03/15/396399.aspx&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Overall this design poses several problems because it exposes internal implementation details directly to the consumer.&amp;nbsp; An improved design should seek to hide the lock from direct access.&amp;nbsp; What we really want is a way to not even provide API’s like Count and Contains unless the object is already in a locked state.&amp;nbsp; This prevents them from being used at all in an incorrect scenario.&lt;/p&gt;

&lt;p&gt;Lets run with this idea to design a more usable thread safe queue.&amp;nbsp; First we’ll divide the interface for a queue into two parts.&amp;nbsp; &lt;/p&gt;

&lt;ol&gt;
  
&lt;li&gt;All procedures that have 0 reliance on the internal state of the collection.&amp;nbsp; Namely Enqueue, and Clear.&amp;nbsp; No state is required to use these methods &lt;/li&gt;

  
&lt;li&gt;All procedures that rely on the internal state of the collection to function correctly.&amp;nbsp; &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The ThreadSafeQueue class will contain all of the methods in category #1.&amp;nbsp; It will also provide a method which returns an instance of an interface which has all of the methods in category #2.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public interface &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ILockedQueue&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color: rgb(43, 145, 175);"&gt;IDisposable&lt;/span&gt;{&lt;br&gt;    &lt;span style="color: blue;"&gt;int &lt;/span&gt;Count { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; }&lt;br&gt;    &lt;span style="color: blue;"&gt;bool &lt;/span&gt;Contains(T value);&lt;br&gt;    T Dequeue();&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The implementation of this interface object will acquire the internal lock of the original ThreadSafeQueue during construction and hold it for the duration if it’s lifetime.&amp;nbsp; This effectively freezes the queue allowing for decision procedures to be used reliably.&amp;nbsp; Implementing IDisposable and releasing the lock in the Dispose method provides a measure of lifetime management.&amp;nbsp;&amp;nbsp; &lt;/p&gt;

&lt;p&gt;The rest of the code sample is below.&amp;nbsp; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeQueue&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;#region &lt;/span&gt;LockedQueue&lt;br&gt;    &lt;span style="color: blue;"&gt;private sealed class &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;LockedQueue &lt;/span&gt;: &lt;span style="color: rgb(43, 145, 175);"&gt;ILockedQueue&lt;/span&gt;&amp;lt;T&amp;gt; {&lt;br&gt;        &lt;span style="color: blue;"&gt;private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeQueue&lt;/span&gt;&amp;lt;T&amp;gt; m_outer;&lt;br&gt;        &lt;span style="color: blue;"&gt;internal &lt;/span&gt;LockedQueue(&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeQueue&lt;/span&gt;&amp;lt;T&amp;gt; outer) {&lt;br&gt;            m_outer = outer;&lt;br&gt;            &lt;span style="color: rgb(43, 145, 175);"&gt;Monitor&lt;/span&gt;.Enter(m_outer.m_lock);&lt;br&gt;        }&lt;br&gt;&lt;br&gt;        &lt;span style="color: blue;"&gt;#region &lt;/span&gt;ILockedQueue&amp;lt;T&amp;gt; Members&lt;br&gt;        &lt;span style="color: blue;"&gt;public int &lt;/span&gt;Count { &lt;br&gt;            &lt;span style="color: blue;"&gt;get &lt;/span&gt;{ &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_outer.m_queue.Count; }&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;public bool &lt;/span&gt;Contains(T value) {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_outer.m_queue.Contains(value);&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;public &lt;/span&gt;T Dequeue() {&lt;br&gt;            &lt;span style="color: blue;"&gt;return &lt;/span&gt;m_outer.m_queue.Dequeue();&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;#endregion&lt;br&gt;        #region &lt;/span&gt;IDisposable Members&lt;br&gt;        &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Dispose() {&lt;br&gt;            Dispose(&lt;span style="color: blue;"&gt;true&lt;/span&gt;);&lt;br&gt;            &lt;span style="color: rgb(43, 145, 175);"&gt;GC&lt;/span&gt;.SuppressFinalize(&lt;span style="color: blue;"&gt;this&lt;/span&gt;);&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;private void &lt;/span&gt;Dispose(&lt;span style="color: blue;"&gt;bool &lt;/span&gt;disposing) {&lt;br&gt;            &lt;span style="color: rgb(43, 145, 175);"&gt;Debug&lt;/span&gt;.Assert(disposing, &lt;span style="color: rgb(163, 21, 21);"&gt;"ILockedQueue implementations must be explicitly disposed"&lt;/span&gt;); &lt;br&gt;            &lt;span style="color: blue;"&gt;if &lt;/span&gt;(disposing) {&lt;br&gt;                &lt;span style="color: rgb(43, 145, 175);"&gt;Monitor&lt;/span&gt;.Exit(m_outer.m_lock);&lt;br&gt;            }&lt;br&gt;        }&lt;br&gt;        ~LockedQueue() {&lt;br&gt;            Dispose(&lt;span style="color: blue;"&gt;false&lt;/span&gt;);&lt;br&gt;        }&lt;br&gt;        &lt;span style="color: blue;"&gt;#endregion&lt;br&gt;    &lt;/span&gt;}&lt;br&gt;    &lt;span style="color: blue;"&gt;#endregion&lt;br&gt;&lt;br&gt;    private &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Queue&lt;/span&gt;&amp;lt;T&amp;gt; m_queue = &lt;span style="color: blue;"&gt;new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;Queue&lt;/span&gt;&amp;lt;T&amp;gt;();&lt;br&gt;    &lt;span style="color: blue;"&gt;private object &lt;/span&gt;m_lock = &lt;span style="color: blue;"&gt;new object&lt;/span&gt;();&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public &lt;/span&gt;ThreadSafeQueue() { }&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Enqueue(T value) {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_queue.Enqueue(value);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public void &lt;/span&gt;Clear() {&lt;br&gt;        &lt;span style="color: blue;"&gt;lock &lt;/span&gt;(m_lock) {&lt;br&gt;            m_queue.Clear();&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    &lt;span style="color: blue;"&gt;public &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;ILockedQueue&lt;/span&gt;&amp;lt;T&amp;gt; Lock() {&lt;br&gt;        &lt;span style="color: blue;"&gt;return new &lt;/span&gt;&lt;span style="color: rgb(43, 145, 175);"&gt;LockedQueue&lt;/span&gt;(&lt;span style="color: blue;"&gt;this&lt;/span&gt;);&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;

&lt;p&gt;This design now cleanly separates out the two modes by which the collection can be asked.&amp;nbsp; It completely hides the explicit synchronization aspects from the users and replaces it with design patterns (such as IDisposable) that they are likely already familiar with.&amp;nbsp; Now our original bad sample can be rewritten as follows.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue;"&gt;static void &lt;/span&gt;Example1(&lt;span style="color: rgb(43, 145, 175);"&gt;ThreadSafeQueue&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;int&lt;/span&gt;&amp;gt; queue) {&lt;br&gt;    &lt;span style="color: blue;"&gt;using &lt;/span&gt;(&lt;span style="color: blue;"&gt;var &lt;/span&gt;locked = queue.Lock()) {&lt;br&gt;        &lt;span style="color: blue;"&gt;if &lt;/span&gt;(locked.Count &amp;gt; 0) {&lt;br&gt;            &lt;span style="color: blue;"&gt;var &lt;/span&gt;first = locked.Dequeue();&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;No explicit synchronization code is needed by the user.&amp;nbsp; This design makes it much harder for the user to make incorrect assumptions or misuses of the collection.&amp;nbsp; The “decision procedures” are simply not available unless the collection is in a locked state.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;As with most thread safe designs, there are ways in which this code can be used incorrectly &lt;/p&gt;

&lt;ol&gt;
  
&lt;li&gt;
    
&lt;p&gt;Using an instance of ILockedQueue&amp;lt;T&amp;gt; after it’s been disposed.&amp;nbsp; This though is already considered taboo though and we can rely on existing user knowledge to help alleviate this problem.&amp;nbsp; Additionally, static analysis tools, such as FxCop, will flag this as an error.&lt;/p&gt;

    
&lt;p&gt;&amp;nbsp;&lt;/p&gt;

    
&lt;p&gt;With a bit more rigor this can also be prevented. Simply add a disposed flag and check it on entry into every method.&lt;/p&gt;
  &lt;/li&gt;

  
&lt;li&gt;It’s possible for the user to maintain values, such as Count, between calls to Lock and use it to make an incorrect assumption about the state of the list.&amp;nbsp; &lt;/li&gt;

  
&lt;li&gt;If the user fails to dispose the ILockedQueue&amp;lt;T&amp;gt; instance it will be forever locked.&amp;nbsp; Luckily FxCop will also flag this as an error since it’s an IDisposable.&amp;nbsp; It’s not a foolproof mechanism though. &lt;/li&gt;

  
&lt;li&gt;There is nothing that explicitly says to the user “please only use ILockedQueue&amp;lt;T&amp;gt; for a very short time”.&amp;nbsp; IDisposable conveys this message to a point but it’s certainly not perfect.&lt;/li&gt;

  
&lt;li&gt;The actual ILockedQueue&amp;lt;T&amp;gt; implementation is not thread safe.&amp;nbsp; Ideally users won’t pass instances of IDisposable between threads but it is something to think about.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The good news is that two of these flaws (1 and 3) are issues with existing types and tools are already designed to weed them out.&amp;nbsp; FxCop will catch common cases for both of them.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;Also, many of these cases are considered bad code in the absence of a thread safe collection.&amp;nbsp; This allows users to rely on existing knowledge instead of forcing them to learn new design patterns for mutable thread safe collections.&amp;nbsp; &lt;/p&gt;

&lt;p&gt;Overall I feel like this design is a real win over the other versions.&amp;nbsp; It provides an API which helps to limit the mistakes a user can make with a mutable thread safe collection without requiring a huge deal of new patterns in order to use.&amp;nbsp; &lt;/p&gt;
&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9424930" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Threading/default.aspx">Threading</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item></channel></rss>