Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to do C++ style destructors in C#?
    primarykey
    data
    text
    <p>I've got a C# class with a <code>Dispose</code> function via <code>IDisposable</code>. It's intended to be used inside a <code>using</code> block so the expensive resource it handles can be released right away.</p> <p>The problem is that a bug occurred when an exception was thrown before <code>Dispose</code> was called, and the programmer neglected to use <code>using</code> or <code>finally</code>.</p> <p>In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use <code>using</code>.</p> <p>Is there any way to for a <code>using</code> block to be automatically used in C#?</p> <p>Many thanks.</p> <p>UPDATE:</p> <p>I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.</p> <p>Here's the bug I found, reduced to the essentials...</p> <pre><code>try { PleaseDisposeMe a = new PleaseDisposeMe(); throw new Exception(); a.Dispose(); } catch (Exception ex) { Log(ex); } // This next call will throw a time-out exception unless the GC // runs a.Dispose in time. PleaseDisposeMe b = new PleaseDisposeMe(); </code></pre> <p>Using <code>FXCop</code> is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload