8

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.

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

1 Comment

(Just ignore that nonsense about "The CLR converts your code into MSIL" in that article)
4

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.