<?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 : Gotcha</title><link>http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx</link><description>Tags: Gotcha</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><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>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>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>Properly handling a WinForms Timer event</title><link>http://blogs.msdn.com/jaredpar/archive/2008/10/27/properly-handling-a-winforms-timer-event.aspx</link><pubDate>Mon, 27 Oct 2008 15:00:07 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9017488</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>4</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9017488.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9017488</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9017488</wfw:comment><description>&lt;p&gt;The WinForms &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx"&gt;Timer&lt;/a&gt; class allows the user to perform a particular action at a set interval.&amp;#160; Timer objects fire a &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.tick.aspx"&gt;Tick&lt;/a&gt; event at the set time which users can easily respond to.&amp;#160; This is very useful if a developer wants to check for a particular condition say every 2 seconds ( for the remainder of this article I'm going to use 2 seconds as a practical example even though it's really any arbitrary time period).&lt;/p&gt;  &lt;p&gt;Occasionally users are surprised to find that the Tick event will fire much faster than they are expecting.&amp;#160; Instead of waiting for 2 seconds between calls, they event will fire almost immediately after one is finished processing. &lt;/p&gt;  &lt;p&gt;What's going on here is a side effect of how this event works under the hood.&amp;#160; The interval for the timer event is calculated in real world time.&amp;#160; So quite literally every 2 seconds Windows will consider the internal reached and will issue a new tick message.&amp;#160; The next time a WinForms event is not executing developer code a tick event is raised [1].&amp;#160; &lt;/p&gt;  &lt;p&gt;So imagine we had the following code.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Private Sub &lt;/span&gt;OnTimerTick() &lt;span style="color: blue"&gt;Handles &lt;/span&gt;m_timer.Tick
    RunSomeOperation()
&lt;span style="color: blue"&gt;End Sub&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Consider what happens if RunSomeOperation takes longer than 2 seconds.&amp;#160; The Tick event is fired in real time so while we're in the middle of RunSomeOperation, another Tick event is being queued up for processing.&amp;#160; As soon as we leave OnTimerTick we're back in WinForms code which sees a Tick event and promptly raises it which puts us right back in OnTimerTick.&lt;/p&gt;

&lt;p&gt;This is contrary to what most people expect.&amp;#160; Most people expect the Tick event to fire 2 seconds after their code is finished executing.&amp;#160; &lt;/p&gt;

&lt;p&gt;To work around this developers should stop the timer when processing a timer event.&amp;#160; Just before exiting the event handler, re-enable the timer.&amp;#160; This will cause Windows to start calculating the interval from the start.&amp;#160; This has the effect of making the timer event fire 2 seconds after developer code stops executing.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Private Sub &lt;/span&gt;OnTimerTick() &lt;span style="color: blue"&gt;Handles &lt;/span&gt;m_timer.Tick
    m_timer.Stop()
    &lt;span style="color: blue"&gt;Try
        &lt;/span&gt;RunSomeOperation()
    &lt;span style="color: blue"&gt;Finally
        &lt;/span&gt;m_timer.Start()
    &lt;span style="color: blue"&gt;End Try
End Sub&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;[1] This is not 100% true.&amp;#160; It's really whenever the Application begins to pump messages again.&amp;#160; Message pumping, more specifically when it does and does not occur, is too involved for this discussion.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9017488" 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/WinForms/default.aspx">WinForms</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category></item><item><title>Redefining Success</title><link>http://blogs.msdn.com/jaredpar/archive/2008/10/24/redefining-success.aspx</link><pubDate>Fri, 24 Oct 2008 15:00:41 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9010695</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9010695.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9010695</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9010695</wfw:comment><description>&lt;p&gt;Spent about an hour debugging a bit of code today.&amp;#160; I was attempting to read data from a particular source and kept getting back failure codes.&amp;#160; After some debugging I discovered the data didn't actually exist in the source I was reading from.&amp;#160; &lt;/p&gt;  &lt;p&gt;This put me back to investigating where I wrote the data out.&amp;#160; Restarted the scenario and verified that I actually called the data writing API and that it succeeded.&amp;#160; &lt;/p&gt;  &lt;p&gt;Now what?&amp;#160; Well the data clearly wasn't there so I concluded the data writing must be failing in some odd way.&amp;#160; I eventually found the data writing code and was horrified to find the following definition.&lt;/p&gt;  &lt;pre&gt;HRESULT WriteSomeData(...) {
  // We don't support data of this type
  return S_OK;
}&lt;/pre&gt;

&lt;p&gt;Personally I thought this warranted an error code (perhaps E_NOTIMPL).&amp;#160; But given the situation I must conclude the author successfully failed to write the data.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9010695" 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>When can you catch a StackOverflowException?</title><link>http://blogs.msdn.com/jaredpar/archive/2008/10/22/when-can-you-catch-a-stackoverflowexception.aspx</link><pubDate>Wed, 22 Oct 2008 15:00:01 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9010678</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9010678.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9010678</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9010678</wfw:comment><description>&lt;p&gt;Answer: When you're the one who threw it.&amp;#160; &lt;/p&gt;  &lt;p&gt;Starting with the CLR version 2.0, the policy for handling a &lt;a href="http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx"&gt;StackOverflowException&lt;/a&gt; was changed.&amp;#160; User code can no longer handle the exception[1].&amp;#160; Instead the CLR will simply terminate the process.&amp;#160; &lt;/p&gt;  &lt;p&gt;This is not 100% true though.&amp;#160; User code can still handle StackOverflowExceptions which are artificially thrown.&amp;#160; That is thrown by the user instead of resulting from an actual overflow of the stack.&amp;#160; This is in contradiction to the documentation but can be demonstrated with a quick and dirty sample program (see end of the post).&amp;#160; &lt;/p&gt;  &lt;p&gt;This is a trivial point for sure.&amp;#160; Yet I feel the need to point it out because I recently saw a newsgroup conversation where someone posted sample exception logging code and happened to use a StackOverflowException in the sample.&amp;#160; Their sample explicitly threw the exception so it worked and they had good reason to suspect it worked in production as well.&amp;#160; I was equally amazed it worked at all.&amp;#160; &lt;/p&gt;  &lt;p&gt;Please don't take this post as advocating that you should handle a StackOverflowException (you shouldn't).&amp;#160; This is merely an oddity I found interesting.&amp;#160; Personally I'd prefer it not be catch-able in any circumstance. &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static void &lt;/span&gt;CatchStackOverflow1() {
    &lt;span style="color: blue"&gt;try &lt;/span&gt;{
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StackOverflowException&lt;/span&gt;();
    } &lt;span style="color: blue"&gt;catch &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;StackOverflowException &lt;/span&gt;ex) {
        &lt;span style="color: green"&gt;// Executes and handles the exception.  User code continues
        &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(ex.Message);
    }
}

&lt;span style="color: blue"&gt;static int &lt;/span&gt;CreateRealOverflow(&lt;span style="color: blue"&gt;int &lt;/span&gt;p1) {
    &lt;span style="color: blue"&gt;return &lt;/span&gt;42 + CreateRealOverflow(p1 + 1);
}

&lt;span style="color: blue"&gt;public static void &lt;/span&gt;CatchStackOverflow2() {
    &lt;span style="color: blue"&gt;try &lt;/span&gt;{
        CreateRealOverflow(42);
    } &lt;span style="color: blue"&gt;catch &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;StackOverflowException &lt;/span&gt;ex) {
        &lt;span style="color: green"&gt;// Will not execute
        &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(ex.Message);
    }
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[] args) {
    CatchStackOverflow1();
    CatchStackOverflow2();
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;[1] Unless you are hosting the CLR in which case you can implement some recovery mechanism.&amp;#160; This is certainly the exception though and not the rule [2]&lt;/p&gt;

&lt;p&gt;[2] Sorry for the pun&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9010678" 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/Exceptions/default.aspx">Exceptions</category></item><item><title>Regular Expression Limitations</title><link>http://blogs.msdn.com/jaredpar/archive/2008/10/15/regular-expression-limitations.aspx</link><pubDate>Wed, 15 Oct 2008 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8977495</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8977495.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8977495</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8977495</wfw:comment><description>&lt;p&gt;I'm struggling with an introduction line to this blog post so I'm just going to go for bluntness:&amp;#160; Regular expressions are limited and it's important to understand these limitations.&amp;#160; Ok, now that the premise is out of the way, lets go to a sample.&lt;/p&gt;  &lt;p&gt;For a time in college I was a teaching assistant in a introduction to Compiler course [1]. Regex's played a large role in the class and inevitably a question or two would appear on a test and the final.&amp;#160; My favorite question was the following &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Imagine the C block comment token (/* */) was allowed to be recursive.&amp;#160; For example /* /* this is a comment */ */.&amp;#160; Write a regex which will match all C comments.&amp;#160; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We'd get loads of interesting answers but there is only one correct one.&amp;#160; It's not possible.&amp;#160; &lt;/p&gt;  &lt;p&gt;Why?&amp;#160; The keyword in this question is &amp;quot;recursive.&amp;quot;&amp;#160; I prefer to call it &amp;quot;counting&amp;quot; though.&amp;#160; Regular expressions a class of Finite Automata (FA).&amp;#160; One of the properties of FA is they cannot be asked to match anything that is recursive (aka has the equal number of items on left hand side and right hand side).&amp;#160; They lack the sufficient state necessary to do so.&amp;#160; To accurately match this a Context Free Grammar is required.&amp;#160; Enough with the terminology though.&lt;/p&gt;  &lt;p&gt;Critics: Wait, you think asking a trick question on a test is a good idea?&amp;#160; &lt;/p&gt;  &lt;p&gt;Answer: At first no.&amp;#160; I didn't like this question when I encountered it as a student and it took me a precious 10 minutes to answer.&amp;#160; I knew the answer right off the bat but I was hesitant to write it down.&amp;#160; As a TA I liked this question slightly more.&amp;#160; Namely because we drilled on this point from day 1 and most students would still miss the question [2].&lt;/p&gt;  &lt;p&gt;I didn't truly appreciate this question until I started working professionally.&amp;#160; I often see people struggling to create a functioning regex for patterns that it cannot possibly work for.&amp;#160; One of the first places I saw it was in a piece of code that QA was (naturally) having a field day with.&amp;#160; I was brought it for a code review and after seeing the regex and the problem I pointed out that it wouldn't be possible.&amp;#160; It took a few minutes but I was able to convince them a regex wouldn't work.&amp;#160; Up until that point no one had considered there wasn't a regex solution, just that the one they had wasn't good enough.&amp;#160; Days were wasted in this venture.&lt;/p&gt;  &lt;p&gt;Part of being a good programmer is recognizing the strengths and weakness's of your tools.&amp;#160; Most importantly though is knowing the limitations.&amp;#160; It will save you hours and potentially days of wasted work.&amp;#160;&amp;#160; &lt;/p&gt;  &lt;p&gt;As an exercise which of the following can a regex help with (answer at bottom under [3])?&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;A C# string &lt;/li&gt;    &lt;li&gt;A C# string literal &lt;/li&gt;    &lt;li&gt;An XML element &lt;/li&gt;    &lt;li&gt;An XML attribute &lt;/li&gt;    &lt;li&gt;A file system path &lt;/li&gt;    &lt;li&gt;A C/VB/C# math expression &lt;/li&gt;    &lt;li&gt;Email address &lt;/li&gt;    &lt;li&gt;Matching a valid regex &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;As a side note, there are several regex engines out there that support the notion of recursion.&amp;#160; These will allow you to match these types of patterns but are not technically regexs in the strictest since of the word.&amp;#160; These are not strictly speaking regular expressions in computing theory but recursive extensions are quickly becoming a part of many libraries.&amp;#160; &lt;/p&gt;  &lt;p&gt;In a future (hopefully soon) post I will explore the recursive extensions to the .Net regular expression language. &lt;/p&gt;  &lt;p&gt;[1] It had various names CS2330 is the most infamous&lt;/p&gt;  &lt;p&gt;[2] Even though we would go over it verbatim in class&lt;/p&gt;  &lt;p&gt;[3] Regex will work for 1,2,4,5,7&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8977495" 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/Regex/default.aspx">Regex</category></item><item><title>A Lesson in Serialization</title><link>http://blogs.msdn.com/jaredpar/archive/2008/09/02/a-lesson-in-serialization.aspx</link><pubDate>Tue, 02 Sep 2008 15:00:46 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8904579</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8904579.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8904579</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8904579</wfw:comment><description>&lt;p&gt;A few days ago, I recklessly added a [Serialization] attribute to a few of my immutable collection types.&amp;#160; I needed to pass data between AppDomain's and adding [Serialization] was the quick and dirty fix.&amp;#160; Compiled, ran and I didn't think much about it.&amp;#160; &lt;/p&gt;  &lt;p&gt;Luckily I was updating some unit tests last night and I remembered this and added a couple of serialization sanity tests.&amp;#160; Most of the tests passed first time but for my ImmutableStack class[1] was throwing an exception.&amp;#160; Well, it was actually my ImmutableQueue but it was failing in one of the inner ImmutableStack instances.&amp;#160; The test code was fairly straight forward&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;stack = &lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;.Create(&lt;span style="color: blue"&gt;new int&lt;/span&gt;[] { 1, 2, 3 });
&lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;stream = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MemoryStream&lt;/span&gt;()) {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;f = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BinaryFormatter&lt;/span&gt;();
    f.Serialize(stream,stack);
    stream.Position = 0;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;obj = f.Deserialize(stream);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;stack2 = (&lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;)obj;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;stack3 = stack2.Reverse();
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I did a bit of digging and discovered the exception was coming from the stack2.Reverse() call.&amp;#160; Jumped through the code and didn't see much wrong.&amp;#160; I had several existing tests around ImmutableStack.Reverse() and I couldn't see why Serialization would make any difference.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;T&amp;gt; Reverse() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;r = &lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;T&amp;gt;.Empty;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;current = &lt;span style="color: blue"&gt;this&lt;/span&gt;;
    &lt;span style="color: blue"&gt;while &lt;/span&gt;(current != &lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;T&amp;gt;.Empty) {
        r = r.Push(current.Peek());
        current = current.Pop();
    }

    &lt;span style="color: blue"&gt;return &lt;/span&gt;r;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Can you see what's wrong with the code?&lt;/p&gt;

&lt;p&gt;It took me a few minutes of debugging and frustration.&amp;#160; The bug is in the while loop conditional.&amp;#160; Until you introduce serialization this code is just fine.&amp;#160; ImmutableStack&amp;lt;T&amp;gt;.Empty is a static readonly declaration.&amp;#160; The code implementation only allows for one to be created so it a singleton and equality can be done with a quick reference check. &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;private static readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EmptyImmutableStack &lt;/span&gt;s_empty = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;EmptyImmutableStack&lt;/span&gt;();

&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;T&amp;gt; Empty {
    &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;s_empty; }
}&lt;/pre&gt;

&lt;p&gt;Unfortunately serialization breaks the assumption that EmptyImmutableStack is a singleton.&amp;#160; The EmptyImmutableStack class is a singleton by convention only.&amp;#160; It's a private nested class that's only instantiated once per AppDomain.&amp;#160; There is nothing stopping the CLR or Serialization for that matter from creating a second instance.&amp;#160; In the case of deserialization that's exactly what happens.&amp;#160; The serializer isn't built to recognize this pattern and instead simply creates a new instance of EmptyImmutableStack upon deserialization.&amp;#160; &lt;/p&gt;

&lt;p&gt;This essentially prevents you from safely using a functional style Empty pattern inside a serializable collection.&amp;#160; &lt;/p&gt;

&lt;p&gt;The fix is simple enough, alter the conditional to be (!current.IsEmpty).&amp;#160; &lt;/p&gt;

&lt;p&gt;[1] The version of ImmutableStack I'm using is heavily based off of &lt;a href="http://blogs.msdn.com/ericlippert/archive/2007/12/04/immutability-in-c-part-two-a-simple-immutable-stack.aspx"&gt;Eric Lippert's implementation&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8904579" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Testing/default.aspx">Testing</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category></item><item><title>Don't mix using statements and lambda expressions</title><link>http://blogs.msdn.com/jaredpar/archive/2008/07/16/don-t-mix-using-statements-and-lambda-expressions.aspx</link><pubDate>Wed, 16 Jul 2008 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8735248</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>15</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8735248.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8735248</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8735248</wfw:comment><description>&lt;P&gt;Title pretty much says it all but what good is a rule without any explanation.&amp;nbsp; The main issue here is that at the core, using statements and lambda expressions both alter variable lifetimes.&amp;nbsp; Unfortunately they alter the lifetime in different directions.&amp;nbsp; Using will shorten the life time of a variable to the specified block.&amp;nbsp; This is a somewhat artificial way because the object is still technically alive but can't be trusted to do anything.&amp;nbsp; Lambda expressions take a variable limited to a specific scope and extends their lifetime to potentially be that of a heap value. Anytime two features alter the attribute of a variable in different directions, they can probably cause problems when used in conjunction.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Take the following contrived but real example.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;static&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Future&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt; Example() {
            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;using&lt;/SPAN&gt; (&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; obj = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;MyDisosableObject&lt;/SPAN&gt;()) {
                &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;return&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Future&lt;/SPAN&gt;.Create(() =&amp;gt; obj.SomeFunction());
            }
        }&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8735248" 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></item><item><title>Bit by void*</title><link>http://blogs.msdn.com/jaredpar/archive/2008/06/16/bit-by-void.aspx</link><pubDate>Mon, 16 Jun 2008 15:00:07 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8598714</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8598714.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8598714</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8598714</wfw:comment><description>&lt;p&gt;Recently I got bit by void* again because of another C++ quirk I didn't think through.&amp;#160; I had a class which wrapped a void* which could be one of many different structs.&amp;#160; The structs were POD and didn't have any shared functionality hence I didn't bother creating an inheritance hierarchy.&amp;#160; Unfortunately I defined the structs like so&lt;/p&gt;  &lt;pre&gt;class C1 {
  struct S1 {
    int field1;
    float field2;
  };
  struct S2 {
    char field1;
  };
  ~C1() {
    delete m_pData;
  }
  void* m_pData; // Can be S1,S2,etc ...
}&lt;/pre&gt;

&lt;p&gt;Unfortunately this &lt;strong&gt;appeared &lt;/strong&gt;to work fine for quite some time.&amp;#160; Then after a couple of days of bug fixes I ended up with a memory leak which I quickly tracked down to a leaked COM object.&amp;#160; Although C1 was at fault I didn't suspect any changes to this class because after all it was working fine for some time and all I did was add a new field to one of the structs.&amp;#160; If the structs were being successfully free'd before a new field shouldn't change anything.&lt;/p&gt;

&lt;p&gt;The field I added was of type CComPtr&amp;lt;T&amp;gt; which exposed a greater problem in my code.&amp;#160; Even though I properly delete the pointer in C1::~C1() I wasn't running the destructor on the pointed at data and instead I was just freeing the memory.&amp;#160; Until I added a field which had a non-trivial destructor this wasn't a problem (still a bug though).&amp;#160; &lt;/p&gt;

&lt;p&gt;Why did this happen?&amp;#160; By deleting a void* and expecting a destructor to run what I'm really doing is asking C++ to behave polymorphicly.&amp;#160; C++ as a rule won't behave this way unless it is specifically asked to with inheritance and virtual.&amp;#160;&amp;#160; In the case of void*, it just won't.&amp;#160; The fix is to actually implement an inheritance hierarchy which supports polymorphism.&lt;/p&gt;

&lt;p&gt;It's just another rule that I need to remember when coding C++.&amp;#160; &lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Deleting void* is dangerous, period. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Unfortunately C++ has too many of these rules and not enough enforcement.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8598714" 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>Gotcha: CComAutoCriticalSection and copy constructors</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/24/gotcha-ccomautocriticalsection-and-copy-constructors.aspx</link><pubDate>Thu, 24 Apr 2008 15:00:24 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8417161</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8417161.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8417161</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8417161</wfw:comment><description>&lt;p&gt;While investigating a crash during a suite run I found the stack walk included the destructor for a &lt;a href="http://msdn2.microsoft.com/en-us/library/50yhb8t7.aspx"&gt;CComAutoCriticalSection&lt;/a&gt;.&amp;nbsp; This is a fairly reliable class so I immediately suspected my code.&amp;nbsp; I did a couple of quick checks for a double free and didn't find any.&amp;nbsp; Then I looked a little closer at CComAutoCriticalSection and spotted that it doesn't redefine the standard copy and operator= constructor.&lt;/p&gt; &lt;p&gt;This is a red flag for any class that implements RAII.&amp;nbsp; C++ will automatically define a copy/operator= for your clasess which will amount to a memcpy.&amp;nbsp; This means copies of two objects will be managing the same resource.&amp;nbsp; Once the second one is destroyed it will result in a double free and hopefully a crash.&amp;nbsp; &lt;/p&gt; &lt;p&gt;I walked the hierarchy and discovered that none of the base classes redefined these methods either.&amp;nbsp; After that it only took a few minutes to discover the bug.&amp;nbsp; I attempt to pass the object by reference but instead ended up passing it by value.&amp;nbsp; &lt;/p&gt; &lt;p&gt;To ensure I didn't miss any other cases of this, I added the following definition to my code base and moved all instances of CComAutoCriticalSection to point to this version.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; SafeCriticalSection : &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; CComAutoCriticalSection
{
&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt;:
    SafeCriticalSection() {}
&lt;span style="color: rgb(0,0,255)"&gt;private&lt;/span&gt;:
    SafeCriticalSection(&lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; SafeCriticalSection&amp;amp;);
    SafeCriticalSection&amp;amp; &lt;span style="color: rgb(0,0,255)"&gt;operator&lt;/span&gt;=(&lt;span style="color: rgb(0,0,255)"&gt;const&lt;/span&gt; SafeCriticalSection&amp;amp;);
};&lt;/pre&gt;It should be standard practice to define all 3 of the above methods on any class which has RAII semantics.&amp;nbsp; This is not necessary if all of the members are copy safe (CComPtr&amp;lt;&amp;gt; for example). &lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8417161" 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>Immutability and ReadOnlyCollection&lt;T&gt;</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/22/api-design-readonlycollection-t.aspx</link><pubDate>Tue, 22 Apr 2008 15:42:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8415163</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8415163.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8415163</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8415163</wfw:comment><description>&lt;P&gt;I am a huge fan of read only/immutable collections and data.&amp;nbsp; Hopefully the increased exposure through the blogosphere alerted users to the advantages of this type of programming for the appropriate scenarios.&amp;nbsp; I wanted to discuss &lt;A href="http://msdn2.microsoft.com/en-us/library/ms132474.aspx" mce_href="http://msdn2.microsoft.com/en-us/library/ms132474.aspx"&gt;ReadOnlyCollection&amp;lt;T&amp;gt;&lt;/A&gt;&amp;nbsp;in case devs looking around in the BCL discover&amp;nbsp;it and assume it's immutable.&amp;nbsp; There are two details of this class which cause gotchas and design issues for consumers who assume it is immutable.&lt;/P&gt;
&lt;H3&gt;It implements IList&amp;lt;T&amp;gt;&lt;/H3&gt;
&lt;P&gt;&lt;A href="http://msdn2.microsoft.com/en-us/library/5y536ey6.aspx" mce_href="http://msdn2.microsoft.com/en-us/library/5y536ey6.aspx"&gt;IList&amp;lt;T&amp;gt;&lt;/A&gt; is a interface describing mutable collection types which support indexing.&amp;nbsp; ReadOnlyCollection is designed to be read only and cannot fulfill this contract.&amp;nbsp; Therfore every mutable function will throw an exception.&amp;nbsp; IMHO this is not the best design because it is&amp;nbsp;implementing a contract it won't every fullfill.&amp;nbsp; This has the effect of turning what should be a compile time error into a runtime exception (passing a non-mutable collection to an API expecting a mutable collection).&lt;/P&gt;
&lt;P&gt;Unfortunately there is not a good interface to implement.&amp;nbsp; The indexable interfaces are all representative of mutable collection types.&amp;nbsp; It would be nice to add an immutable/read only interface which can be safely implemented.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;    &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;interface&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;IReadOnlyList&lt;/SPAN&gt;&amp;lt;T&amp;gt; : &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;IEnumerable&lt;/SPAN&gt;&amp;lt;T&amp;gt;
    {
        T &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;this&lt;/SPAN&gt;[&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; index] { &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;get&lt;/SPAN&gt;; }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; Count { &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;get&lt;/SPAN&gt;; }
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; IndexOf(T value);
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;bool&lt;/SPAN&gt; Contains(T item);
        &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;void&lt;/SPAN&gt; CopyTo(T[] array, &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt; arrayIndex);
    }&lt;/PRE&gt;
&lt;P&gt;Ideally this would be called IImmutableList&amp;lt;T&amp;gt; but I'm having trouble getting over the double I, double M pattern to start the name.&amp;nbsp; Perhaps IPersistentList.&lt;/P&gt;
&lt;H3&gt;It's not deeply ReadOnly&lt;/H3&gt;
&lt;P&gt;ReadOnlyCollection&amp;lt;T&amp;gt; is a read only facade on top of mutable collection.&amp;nbsp; Read only data should be just that, read only.&amp;nbsp; This means calling methods directly on the class produce the same result every single time.&amp;nbsp; However because it uses a mutable backing store this is not true and can cause gotchas along the road. &lt;/P&gt;
&lt;P&gt;Take the following sample which uses a ReadOnlyCollection to wrap a List.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; list = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;List&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;();
            list.AddRange(&lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Enumerable&lt;/SPAN&gt;.Range(1, 10));

            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; roList = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ReadOnlyCollection&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;(list);
            &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Console&lt;/SPAN&gt;.WriteLine(roList.Count);    &lt;SPAN style="COLOR: rgb(0,128,0)"&gt;// Outputs: 10
&lt;/SPAN&gt;            list.Add(42);
            &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;Console&lt;/SPAN&gt;.WriteLine(roList.Count);    &lt;SPAN style="COLOR: rgb(0,128,0)"&gt;// Outputs: 11&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;There are ways to avoid this problem with ReadOnlyCollectionn.&amp;nbsp; The simplest is to make sure you pass a copy of your list into the constructor.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;            &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;var&lt;/SPAN&gt; roList2 = &lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;ReadOnlyCollection&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;(&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: rgb(43,145,175)"&gt;List&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: rgb(0,0,255)"&gt;int&lt;/SPAN&gt;&amp;gt;(list));&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8415163" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Immutable/default.aspx">Immutable</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>Gotcha: Generic overload resolution when called generically</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/14/gotcha-generic-overload-resolution-when-called-generically.aspx</link><pubDate>Mon, 14 Apr 2008 15:30:07 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8381274</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8381274.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8381274</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8381274</wfw:comment><description>&lt;p&gt;Both VB and C# have a feature of generic overload resolution that is fairly helpful and yet a source of gotchas.&amp;nbsp; Lets say you have two methods with the same number of arguments.&amp;nbsp; One method has arguments with generic types and the other does not.&amp;nbsp; For Example:&lt;/p&gt;&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;C1&lt;/span&gt;&amp;lt;T&amp;gt; {
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; F1(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; ival) {
            &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"Non-generic F1"&lt;/span&gt;);
        }
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; F1(T val) {
            &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"Generic F1"&lt;/span&gt;);
        }
    }&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;Imagine what happens when we have a C1&amp;lt;int&amp;gt; and call F1(5).&amp;nbsp; Which method should the compiler bind to?&amp;nbsp; Both VB and C# when presented with this type of situation will choose the non-generic version.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;            v1.F1(5);           &lt;span style="color: rgb(0,128,0)"&gt;// Binds to Non-generic F1
&lt;/span&gt;            v2.F1(&lt;span style="color: rgb(163,21,21)"&gt;"foo"&lt;/span&gt;);       &lt;span style="color: rgb(0,128,0)"&gt;// Binds to Generic F1&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;At a glance we might think that we can provide specialized behavior for a subset of types that are interesting (similar to C++ template specialization).&amp;nbsp; If VB/C# will bind to our non-generic version then we don't have to due ugly type switching to implement different behavior for certain types.&amp;nbsp; Unfortunately we would be wrong.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;This type of overload resolution only happens if the compiler can statically verify that the argument matches a non-generic overload.&amp;nbsp; So if we call F1 generically it will not bind to the non-generic overload.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; TestOverload&amp;lt;T&amp;gt;(&lt;span style="color: rgb(43,145,175)"&gt;C1&lt;/span&gt;&amp;lt;T&amp;gt; weird, T value) {
            weird.F1(value);
        }

        &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Main(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;[] args) {
            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; v1 = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;C1&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;&amp;gt;();
            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; v2 = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;C1&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;&amp;gt;();

            TestOverload(v1, 5);        &lt;span style="color: rgb(0,128,0)"&gt;// Binds to Generic F1
&lt;/span&gt;            TestOverload(v2, &lt;span style="color: rgb(163,21,21)"&gt;"foo"&lt;/span&gt;);    &lt;span style="color: rgb(0,128,0)"&gt;// Binds to Generic F1
&lt;/span&gt;        }&lt;/pre&gt;&lt;pre class="code"&gt;&amp;nbsp;&lt;/pre&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8381274" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Generics/default.aspx">Generics</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category></item><item><title>Gotcha: CComPtrBase&lt;T&gt; assignment</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/08/gotcha-ccomptrbase-t-assignment.aspx</link><pubDate>Tue, 08 Apr 2008 18:44:16 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8352116</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8352116.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8352116</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8352116</wfw:comment><description>&lt;p&gt;Today what started out as a crash due to a pure virtual call turned into finding a gotcha in CComPtrBase&amp;lt;T&amp;gt;.&amp;nbsp; Essentially the code in question boiled down to the following.&amp;nbsp; Can you spot the problem?&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; GetAStudent(CComPtrBase&amp;lt;T&amp;gt; &amp;amp;spStudent)
{
    CComPtr&amp;lt;Student&amp;gt; spLocal;
    &lt;span style="color: rgb(0,128,0)"&gt;// Do some operation to get a student
&lt;/span&gt;    spLocal = spStudent;
}&lt;/pre&gt;
&lt;p&gt;The problem isn't apparent until you look at the definition for CComPtrBase&amp;lt;T&amp;gt;::operater =.&amp;nbsp; See the problem?&amp;nbsp; Basically CComPtrBase&amp;lt;T&amp;gt;::operator= isn't explicitly defined.&amp;nbsp; This means that C++ will automatically implement &lt;a href="http://msdn2.microsoft.com/en-us/library/x0c54csc(VS.71).aspx"&gt;memberwise assignment.&lt;/a&gt;&amp;nbsp; The RHS of the operator= will be a "const CComPtrBase&amp;lt;T&amp;gt;&amp;amp;".&amp;nbsp; &lt;/p&gt;
&lt;p&gt;CComPtr&amp;lt;T&amp;gt; derives from CComPtrBase&amp;lt;T&amp;gt; therefore it satisfies this and a memberwise assignment will occur.&amp;nbsp; We now have two smart pointers on the same value.&amp;nbsp; However the second smart pointer, CComPtrBase&amp;lt;T&amp;gt;, did not perform an AddRef.&amp;nbsp; So when both objects are destroyed there will be an extra Release and hopefully a crash.&lt;/p&gt;
&lt;p&gt;The fix? &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Use CComPtr&amp;lt;T&amp;gt; or CComPtrEx&amp;lt;T&amp;gt; instead of CComPtrBase&amp;lt;T&amp;gt;&lt;/li&gt;
&lt;li&gt;Less Optimal: call AddRef() on spLocal.&amp;nbsp;&amp;nbsp; &lt;/li&gt;&lt;/ol&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8352116" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Templates/default.aspx">Templates</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category></item><item><title>Get-Content and File Names</title><link>http://blogs.msdn.com/jaredpar/archive/2008/02/02/get-content-and-file-names.aspx</link><pubDate>Sat, 02 Feb 2008 21:55:21 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7397157</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7397157.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7397157</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7397157</wfw:comment><description>&lt;p&gt;Another day, another PowerShell feature discovered.&amp;#160; Unfortunately this time it was a feature that made me think I had a bug in my script.&amp;#160; The script read through some directories, did some file parsing and created a data object for every directory in the form of a &lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/11/29/tuples-in-powershell.aspx"&gt;Tuple&lt;/a&gt;.&amp;#160; &lt;/p&gt;  &lt;p&gt;One of the files was People.txt and contained a list of relevant people for the data (one per line).&amp;#160; Unfortunately the parameter kept showing up like so ...&lt;/p&gt;  &lt;p&gt;People   &lt;br /&gt;------    &lt;br /&gt;{People.txt, People.txt, People.txt, People.txt}&lt;/p&gt;  &lt;p&gt;Confusion set in as to what I did wrong since the code in question amounted to the following.&lt;/p&gt;  &lt;p&gt;D:\temp&amp;gt; new-tuple &amp;quot;People&amp;quot;,(gc People.txt)&lt;/p&gt;  &lt;p&gt;Next step is manual verification&lt;/p&gt;  &lt;p&gt;D:\temp&amp;gt; gc People.txt   &lt;br /&gt;jared    &lt;br /&gt;jamie    &lt;br /&gt;jason    &lt;br /&gt;mary&lt;/p&gt;  &lt;p&gt;So far so good.&amp;#160; Then a tried the explicit tuple code and got back the People.txt problem.&amp;#160; Eventually I decided to try out get-member and see exactly what I had in the array.&amp;#160; It was a string type as expected but then I noticed the following ... extra items.&lt;/p&gt;  &lt;p&gt;D:\temp&amp;gt; gc People.txt | gm &lt;/p&gt;  &lt;p&gt;&amp;#160;&amp;#160; TypeName: System.String &lt;/p&gt;  &lt;p&gt;Name&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; MemberType&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Definition   &lt;br /&gt;----&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ----------&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ----------    &lt;br /&gt;...&lt;/p&gt;  &lt;p&gt;PSParentPath&amp;#160;&amp;#160;&amp;#160;&amp;#160; NoteProperty&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.String PSParentPath=D:\temp   &lt;br /&gt;PSPath&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; NoteProperty&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.String PSPath=D:\temp\People.txt    &lt;br /&gt;PSProvider&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; NoteProperty&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Management.Automation.Provider...    &lt;br /&gt;ReadCount&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; NoteProperty&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Int64 ReadCount=1    &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;It turns out that when you read information from a file in PowerShell they will handily add in the file information as NoteProperty instances.&amp;#160; All well and good and I can see where that would be useful but for now it's really messing up my display.&amp;#160; To remove it just tell powershell that I really just want a string.&lt;/p&gt;  &lt;p&gt;D:\temp&amp;gt; new-tuple &amp;quot;People&amp;quot;,(gc People.txt | %{[string]$_}) &lt;/p&gt;  &lt;p&gt;People   &lt;br /&gt;------    &lt;br /&gt;{jared, jamie, jason, mary}&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7397157" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/PowerShell/default.aspx">PowerShell</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Gotcha/default.aspx">Gotcha</category></item></channel></rss>