I asked a question about returning a Disposable ( IDisposable ) object from a function , but I thought I would confuse the discussion if I raised this question there.
I have created some code examples:
class UsingTest { public class Disposable : IDisposable { public void Dispose() { var i = 0; i++; } } public static Disposable GetDisposable(bool error) { var obj = new Disposable(); if (error) throw new Exception("Error!"); return obj; } }
I encoded it so intentionally because then I call:
using (var tmp = UsingTest.GetDisposable(true)) { }
Using the debugger, I notice that the Dispose method is never executed, although we have already created an instance of the Disposable object. If I understood the purpose of Dispose correctly, if this class actually opened descriptors and the like, we would not close them as soon as we finished with them.
I ask this question because this behavior is consistent with what I would expect, but in the answers to the corresponding question, people seemed to indicate that using would take care of everything.
If using still takes care of all this, can someone explain what I am missing? But if this code can really cause a resource leak, how would you suggest the GetDisposable code ( GetDisposable that I have to instantiate the IDisposable and run the code that can throw an exception before the return statement)?
c # idisposable using-statement
palswim
source share