124

I've the following code

using(MemoryStream ms = new MemoryStream())
{
     //code
     return 0;
}

The dispose() method is called at the end of using statement braces } right? Since I return before the end of the using statement, will the MemoryStream object be disposed properly? What happens here?

1
  • Aaap... I take that back. I just found a near duplicate, after some very dedicated searching: stackoverflow.com/questions/2641692/… Now, the question is asked entirely differently, but the ultimate question is pretty much the same. I suppose we can consider this a dupe after all.
    – Randolpho
    Jul 14, 2010 at 15:46

5 Answers 5

182

Yes, Dispose will be called. It's called as soon as the execution leaves the scope of the using block, regardless of what means it took to leave the block, be it the end of execution of the block, a return statement, or an exception.

As @Noldorin correctly points out, using a using block in code gets compiled into try/finally, with Dispose being called in the finally block. For example the following code:

using(MemoryStream ms = new MemoryStream())
{
     //code
     return 0;
}

effectively becomes:

MemoryStream ms = new MemoryStream();
try
{
    // code
    return 0;
}
finally
{
    ms.Dispose();
}

So, because finally is guaranteed to execute after the try block has finished execution, regardless of its execution path, Dispose is guaranteed to be called, no matter what.

For more information, see this MSDN article.

Addendum:
Just a little caveat to add: because Dispose is guaranteed to be called, it's almost always a good idea to ensure that Dispose never throws an exception when you implement IDisposable. Unfortunately, there are some classes in the core library that do throw in certain circumstances when Dispose is called -- I'm looking at you, WCF Service Reference / Client Proxy! -- and when that happens it can be very difficult to track down the original exception if Dispose was called during an exception stack unwind, since the original exception gets swallowed in favor of the new exception generated by the Dispose call. It can be maddeningly frustrating. Or is that frustratingly maddening? One of the two. Maybe both.

5
  • 4
    I think you'll find it's effectively compiled into a try-finally block with a call to Dispose in finally, so it's effectively working off the implementation of finally, as you describe.
    – Noldorin
    Jul 14, 2010 at 15:21
  • @Noldorin: exactly. Although I suppose I could be explicit about that. Edit forthcoming....
    – Randolpho
    Jul 14, 2010 at 15:22
  • 1
    Also note that there are some circumstances in which the finally block is not guaranteed to execute, such as using Environment.FailFast and if a StackOverFlowException occurs. Jul 14, 2010 at 15:44
  • @C.McAtackney: also a good point. Also, IIRC, OutOfMemoryException; basically if you can't catch the exception because it's a critical execution failure, Dispose won't be called. Of course, in such a case the program is guaranteed to crash, along with any memory allocated to it, so in 99.9% of cases it's a non-issue, unless you're doing wonky stuff like writing to a file in your dispose method. Aside from the catastrophic program crash, that is.
    – Randolpho
    Jul 14, 2010 at 15:51
  • You should never use the 'using()' statement with WCF - refer to this article for more info. Here's a snippet I use for WCF proxies:' WCFProxy variableName = null; try { variableName = new WCFProxy(); // TODO code here variableName.Proxy.Close(); variableName.Dispose(); } catch (Exception) { if (variableName != null && variableName.Proxy != null) { variableName.Proxy.Abort(); } throw; } '
    – Dave Black
    Apr 5, 2011 at 20:52
19

using statements behave exactly like try ... finally blocks, so will always execute on any code exit paths. However, I believe they are subject to the very few and rare situations in which finally blocks are not called. One example that I can remember is if the foreground thread exits while background threads are active: all threads apart from the GC are paused, meaning finally blocks are not run.

Obvious edit: they behave the same apart from the logic that lets them handle IDisposable objects, d'oh.

Bonus content: they can be stacked (where types differ):

using (SqlConnection conn = new SqlConnection("string"))
using (SqlCommand comm = new SqlCommand("", conn))
{

}

And also comma-delimited (where types are the same):

using (SqlCommand comm = new SqlCommand("", conn), 
       comm2 = new SqlCommand("", conn))
{

}
2
  • 1
    According to another answer in stackoverflow stackoverflow.com/a/9396151/6142097, for the second example (comma-delimited), the type of the second parameter should not be specified.
    – mihkov
    Nov 24, 2020 at 9:38
  • @mihkov Good point, just tried this myself. I didn't back track to previous language versions though so I can't tell if this was always the case, or a minor change with Roslyn. Nov 24, 2020 at 21:43
4

Your MemoryStream object will be disposed properly, no need to worry about that.

3

With the using statement, the object will be disposed of regardless of the completion path.

Further reading...

0

Take a look at your code in reflector after you compile it. You'll find that the compiler refactors the code to ensure that dispose is called on the stream.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.