Consider the following classes:
class C1 : IDisposable {...} class C2 : IDisposable {...} sealed class C3 : IDisposable { public C3() { c1 = new C1(); throw new Exception();
Now suppose we are using the disposable object correctly:
using (var c3 = new C3()) { }
How about this piece of code?
In this case, we cannot call the Dispose method because our object never exists.
We know that in this case the finalizer will be called, but there we can only dispose of CriticalFinilizedObjects, and we cannot dispose of objects C1 or C2.
My solution is pretty simple:
sealed class C3 : IDisposable { public C3() { try { c1 = new C1(); throw new Exception();
This solution may differ in some details, but I think you can understand the key principle: if the constructor throws an exception, we forcibly release the received resources and suppress the completion.
Are there any other ideas, suggestions or better solutions?
PS Herb Sutter on his blog ( http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-cc-and-java/ ) opened the question, but he did not offer a solution.
c #
Sergey Teplyakov
source share