Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Consider this code snippet
C#
using(MemoryStream ms = new MemoryStream())
{
     //code
     return ms;
}
Will ms get disposed? And if it does, when?
Posted
Comments
PhilLenoir 25-Sep-14 16:47pm    
My bad, I didn't spot that you were returning a reference. I'd never use a Using block in this case, so I'm not certain that the returned object would be valid. You can easily test this yourself by checking the object in the calling code.
Sergey Alexandrovich Kryukov 25-Sep-14 16:49pm    
Returning a reference from this point is a wrong thing. On a closing '}', ms.Dispose() call is generated.
—SA
Jörgen Andersson 25-Sep-14 17:19pm    
I did test and Piebald is spot on, but what I'm curious about isn't just this simple example, but rather might happen in fringe cases where IDisposable is badly implemented.

Dispose will be called before the item is returned, therefore the returned item is unlikely to be useful, but it depends on the implementation of the actual class. In most cases, any access to the item should result in an ObjectDisposedException.

Don't return or otherwise make the item available outside the confines of the using block.

C#
public X x ;

using ( X y = new X() ) { x = y } ;


Is just as bad.
 
Share this answer
 
Comments
Jörgen Andersson 25-Sep-14 17:11pm    
You say most cases, in which cases don't you get an ObjectDisposedException?
PIEBALDconsult 25-Sep-14 17:30pm    
As you said "cases where IDisposable is badly implemented". I'd say "try it", but really you shouldn't.
This code
C#
using(MemoryStream ms = new MemoryStream())
{
     //code
     //return ms; I commented it out because it makes no sense at all
}

is strictly equivalent to:
C#
MemoryStream ms = new MemoryStream();
try
{
     //code
}
finally
{
    ms.Dispose();
}

In other words, this is an automatic way of calling IDisposable.Dispose(). A note for the author of Solution 1: In general case, disposal have nothing to do with garbage collection and reclaiming memory. In fact, IDisposable often used in reclaiming unmanaged memory, but there are many other uses.

Please see:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx[^],
Understanding the 'using' statement in C#[^],
http://msdn.microsoft.com/en-us/library/system.idisposable%28v=vs.110%29.aspx[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900