Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Because you don't have to allocate the variables in a using() statement - why not use 'stacked' using statements for this?</p> <pre><code>void Dispose() { // the example in the question didn't use the full protected Dispose(bool) pattern // but most code should have if (!disposed) { if (disposing) { ... using (m_foo) using (m_bar) { // no work, using statements will check null // and call Dispose() on each object } m_bar = null; m_foo = null; } </code></pre> <p>The 'stacked' using statements are expanded like this:</p> <pre><code>using (m_foo) { using (m_bar) { /* do nothing but call Dispose */ } } </code></pre> <p>So the Dispose() calls are put in seperate finally blocks:</p> <pre><code>try { try { // do nothing but call Dispose } finally { if (m_bar != null) m_bar.Dispose(); } finally { if (m_foo != null) m_foo.Dispose(); } </code></pre> <p>I had a hard time finding a reference for this in one place. The 'stacked' using statements are found in an <a href="http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae" rel="nofollow noreferrer">old Joe Duffy blog post</a> (see section 'C# and VB Using Statement, C++ Stack Semantics'). The Joe Duffy post is referenced by many StackOverflow answers on IDisposable. I also found a <a href="https://stackoverflow.com/questions/1329739/nested-using-statements-in-c">recent question</a> where stacked using statements for local variables appear to be common. I couldn't find the chaining of finally blocks anywhere but the <a href="http://go.microsoft.com/fwlink/?LinkId=64165" rel="nofollow noreferrer">C# language spec</a> (section 8.13 in C# 3.0 spec), and only for multiple varaibles within a single 'using' block, which isn't exactly what I'm proposing, but if you disasemble the IL you'll find the try/finally blocks are nested. On the null check, also from the C# spec: 'If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.'</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.
    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