title: Can I stop C++/CLI from adding IDisposable to my ref class?
body: <p>C++/CLI helpfully generates the <code>IDisposable</code> scaffolding for you when you implement a destructor on a ref class. Also, if you don't implement a destructor, but your class has a member variable which implements <code>IDisposable</code>, then <code>IDisposable</code> is again automatically implemented on your class. It's pretty helpful and much better than how <code>IDisposable</code> is handled in C#.</p>
  
  <p>I have run into this behaviour when implementing a ref class that holds onto an <code>msclr::com::ptr</code> (a smart pointer that contains an RCW).</p>
  
  <pre><code>ref class Test /* : IDisposable added by the compiler */
  {
    msclr::com::ptr&lt;IWhatever&gt; _aComObject;
  }
  </code></pre>
  
  <p>In <em>my specific case</em>, the COM object referenced by my class doesn't 'lock' some unmanaged resource, it effectively just uses up a bit of unmanaged memory that the CLR can't see. Therefore I would like to avoid confusing the users of my ref class by not implementing <code>IDisposable</code> the class. Instead I want to make the CLR aware of the existence of the COM object by using the GC API to add the appropriate memory pressure.</p>
  
  <p>So, the question is: is there a way to suppress implementation of <code>IDisposable</code> on a ref class that doesn't implement a destructor, but does hold an <code>IDisposable</code> member variable?</p>
  
  <p><strong>NB:</strong> often this would be the wrong thing to do, as it would prevent users of the class from deterministically disposing of the underlying COM object, but given the particular circumstances, exposing <code>IDisposable</code> has the potential to confuse users of my ref class, since it really is not necessary to Dispose of the ref class in question.</p>
  
  <p>I suppose one option would be to implement a variant of msclr::com::ptr without a destructor.</p>
  
  <p>Any other method to suppress the automatic addition of IDisposable would be appreciated. Thanks.</p>
  
  <hr>
  
  <h2>Answer</h2>
  
  <p>Declare <code>_aComObject</code> as a handle to an msclr::com::ptr (<code>msclr::com::ptr&lt;IWhatever&gt;^</code>). The compiler does not then regard <code>Test</code> as being the 'owner' of the com ptr object, and does not Dispose it when Test is deleted.</p>