Search code examples
c#methodsreturndisposeidisposable

Is IDisposable object disposed itself after RETURN from method?


Let's say, I have the following code:

theIDisposableObject myMethod()
{
   theIDisposableObject smth=new theIDisposableObject();
   return smth;
}

void Main()
{
    var A= myMethod();
    ...
    A.Dispose();
}

Do I do it correctly? i mean, is smth disposed on itself, because it is referred to by A variable (which is being disposed), or even smth needs its own disposal (if so, only with using is the solution)?


Solution

  • Is the object disposed? Yes.

    Is there a better way? Yes. Use the using statement.

    AnIDisposableObject myMethod()
    {
       AnIDisposableObject smth=new AnIDisposableObject();
       return smth;
    }
    
    (...)
    
    using( var a = myMethod()) 
    {
    
    }
    // a is disposed here.
    

    This is important because if an exception is thrown between var A= myMethod(); and A.Dispose(); A would not be disposed. Bad.


    C#8

    In C#8 things get even easier.

    if (...) 
    { 
       using FileStream f = new FileStream(@"C:\users\jaredpar\using.md");
       // statements
    }
    
    // Equivalent to 
    if (...) 
    { 
       using (FileStream f = new FileStream(@"C:\users\jaredpar\using.md")) 
       {
        // statements
       }
    }
    

    The lifetime of a using local will extend to the end of the scope in which it is declared. The using locals will then be disposed in the reverse order in which they are declared.

    { 
        using var f1 = new FileStream("...");
        using var f2 = new FileStream("..."), f3 = new FileStream("...");
        ...
        // Dispose f3
        // Dispose f2 
        // Dispose f1
    }