TheAJ
TheAJ

Reputation: 10875

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

Upvotes: 8

Views: 756

Answers (3)

RedEye
RedEye

Reputation: 861

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

Upvotes: 4

Simon Buchan
Simon Buchan

Reputation: 13245

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

Upvotes: 11

Michael Stum
Michael Stum

Reputation: 180944

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

Upvotes: 4

Related Questions