Handling IDisposable in failed initializer or constructor
You should catch any exceptions in the constructor, then dispose of your child objects, then rethrow the original exception (or a new exception that provides additional information).
public class SomethingDisposable : IDisposable
{
System.Diagnostics.Process disposableProcess;
public SomethingDisposable()
{
try
{
disposableProcess = new System.Diagnostics.Process();
// Will throw an exception because I didn't tell it what to start
disposableProcess.Start();
}
catch
{
this.Dispose();
throw;
}
}
public void Dispose()
{
if (disposableProcess != null)
{
disposableProcess.Dispose();
disposableProcess = null;
}
}
}