title: Calling Dispose method inside constructor which throws an exception or behaves unexpectedly
body: <p>I have a class which consumes some unmanaged resources and I would like to free them deterministically and request that the finalizer not be called for the object at hand. My <code>Dispose()</code> method of the class accomplishes this. </p>
  
  <p>In the event of an exception being thrown or something otherwise going wrong or behaving unexpectedly in the constructor, I would like to call <code>Dispose()</code> before throwing. However, I rarely come across implementations which catch thrown exceptions or handle an error in the constructor of disposable objects and then invoke <code>Dispose()</code> on the object - In a lot of cases the author leaves the cleanup to the finalizer. I have not read anything which states that calling <code>Dispose()</code> in a failed constructor is bad practice, but while looking through the .NET source code I have yet to come across such exception or error handling in a disposable object constructor. </p>
  
  <p>Can I call <code>Dispose()</code> inside a "failed" constructor and still be considered a good coding citizen?</p>
  
  <p><strong>Edit to clarify</strong> - I am talking about inside the constructor:</p>
  
  <pre><code>public class MyClass : IDisposable
  {
       private IntPtr _libPtr = IntPtr.Zero;
  
       public MyClass(string dllPath)
       {
           _libPtr = NativeMethods.LoadLibrary(dllPath);
  
           if (_libPtr != IntPtr.Zero)
           { 
               IntPtr fxnPtr = NativeMethods.GetProcAddress(_libPtr, "MyFunction");
               if (fxnPtr == IntPtr.Zero)
               {
                   Dispose(); // Cleanup resources - NativeMethods.FreeLibrary(_libPtr);
                   throw new NullReferenceException("Error linking library."); 
               }
           }
           else
           {
               throw new DllNotFoundException("Something helpful");
           }
       } 
  
       // ...
  } 
  </code></pre>