views:

145

answers:

3

Hello,

Suppose I have a method like so:

public byte[] GetThoseBytes()
{
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
        ms.WriteByte(1);
        ms.WriteByte(2);
        return ms.ToArray();
    }
}

Would this still dispose the 'ms' object? I'm having doubts, maybe because something is returned before the statement block is finished.

Thanks, AJ.

+4  A: 

Yes, Using creates a try..finally block, so it disposes the ms (and even does a null check in case you set ns to null).

Michael Stum
(Just ignore that nonsense about "The CLR converts your code into MSIL" in that article)
Michael Stum
+9  A: 

Yes. using (x = e) { s } is sugar for { x = e; try { s } finally { x.Dispose(); } }

Simon Buchan
And a return inside the body of a try..finally will execute the finally clause before the return actually happens.
dthorpe
@dthorpe: Umm, yeah. Whoops :)
Simon Buchan
+4  A: 

Yes, the whole idea behind the Using statement is that it automatically disposes of whatever stream/object you are "using". nicely done.

RedEye