Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET/C# - Disposing an object with the 'using' statement

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.

like image 640
TheAJ Avatar asked Apr 14 '10 23:04

TheAJ


2 Answers

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

like image 182
Simon Buchan Avatar answered Sep 21 '22 19:09

Simon Buchan


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).

like image 37
Michael Stum Avatar answered Sep 22 '22 19:09

Michael Stum