Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a guarantee on the order in which the Dispose() method is called when using multiple using statements for the same scope in C#?

using (Stuff1 stf1 = new Stuff1(...)) // Allocation of stf1
using (Stuff2 stf2 = new Stuff2(...)) // Allocation of stf2
{
    try
    {
        // ... do stuff with stf1 and stf2 here ...
    }
    catch (Stuff1Exception ex1)
    {
        // ...
    }
    catch (Stuff2Exception ex2)
    {
        // ...
    }
} // Automatic deterministic destruction through Dispose() for stf1/stf2 - but in which order?

In other words, is stf2's Dispose() method guaranteed to be called first and then stf1's Dispose() method guaranteed to be called second? (basically: Dispose() methods being called in reverse order of the allocation of the object that they belong to?)

like image 916
user972301 Avatar asked Dec 17 '22 08:12

user972301


1 Answers

using statements are no different than other block level statements. If you wrote code like this:

if (...)
    if (...)
    {

    }

It would be clear to you what order things take place (not that I would recommend that particular structure), because it's exactly the same as this:

if (...)
{
    if(...)
    {

    }
}

So it is with using. Your code is no different than the following:

using (...)
{
    using(...)
    {

    }
}

Here, it is perfectly clear that the inner using block terminates first, and so it's resource should be disposed first.

like image 125
Joel Coehoorn Avatar answered Feb 22 '23 23:02

Joel Coehoorn