When in instantiate any IDisposable
object, you can do so with a using
statement. Any time the execution returns from the scope of a using
, the object will be disposed. This includes returns and exceptions.
using (var obj = new Connection()) {
throw new Exception("This will dispose of obj");
}
When you build a class that needs a persistent IDisposable
object like yours, you should also make your own class IDisposable
, and dispose of those objects in the Dispose()
method:
public class MyClass : IDisposable
{
Connection con = new Connection();
public void Dispose()
{
con.Dispose();
}
}
Then when you instantiate your own class, use using
, and everything will be happily disposed of when appropriate.
using (var obj = new MyClass()) {
throw new Exception("This will dispose of obj, and obj.con");
}
Ultimately, the later solution is best, because:
- you create resources when necessary
- reuse them efficiently
- and dispose of them properly