Is there any nice pattern in .Net for ensuring that IDisposable fields owned by an object will get disposed if an exception is thrown during construction, possi
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;
}
}
}