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

Asked

Viewed 34 times

2

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

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

In this case, will the resources used by Acd be dispensed with? Or will the flow break keep the resources allocated?

2 answers

3


Yeah, it’s a syntax-sugar with exactly the same operation as Try-Finally:

var acd = new AlgumaClasseIDisposable();
try
{
    return FazAlgumaCoisa(acd);
}
finally
{
    acd.Dispose();
}

3

The answer is: will be released yes.

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

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

Will it actually:

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

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

Tip: To better understand how it works, implement the second form of the code and the debug line by line. So you’ll understand what the execution flow looks like.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.