If I return something inside a using, will the resources be released?

2

I know that using is used to release (give dispose ) resources. My question is in the following case:

public void FuncNaoFazNada()
{
    using(var acd = new AlgumaClasseIDisposable())
    {
        return;
    }
}

In this case, will the resources used by ACD be waived? Or will the flow break keep the resources allocated?

    
asked by anonymous 17.08.2016 / 16:02

2 answers

3

Yes, it is a syntax-sugar that works exactly like try-finally:

var acd = new AlgumaClasseIDisposable();
try
{
    return FazAlgumaCoisa(acd);
}
finally
{
    acd.Dispose();
}
    
17.08.2016 / 16:07
3

The answer is: it will be released yes.

using in C # is a syntactic sugar, which is nothing more than a try ... finally at the end, where this code is:

public void FuncNaoFazNada()
{
    using(var acd = new AlgumaClasseIDisposable())
    {
        return;
    }
}

It will indeed be:

public void FuncNaoFazNada()
{
    var acd = new AlgumaClasseIDisposable();
    try{
        return;
    }
    finally{
        acd.Dispose();
    }
}

So despite return within try , it will always execute the finally code block.

  

Tip: To better understand how the code implements the second form of code and debug line by line. This way you will understand how the execution flow is.

    
17.08.2016 / 16:12