closing and disposing

K

keithv

I came across the following code snippet in a project
I inherited. Having 2 close() and 2 dispose() calls for
essentially one stream seems to me to be way too much
overkill.

What is the proper idiom for this?

MemoryStream memStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memStream);
// ...use writer
writer.Close();
byte[] data = memStream.ToArray();
memStream.Close();
((IDisposable)writer).Dispose();
((IDisposable)memStream).Dispose();
return data;


Thanks,
Keith
 
G

Guest

In fact all you need to do is close the file, and any one of the four calls
will do that.

The best way to do this, however is to use C#'s using construction...
using (MemoryStream memStream = new MemoryStream())
{
BinaryWriter writer = new BinaryWriter(memStream);
// ...use writer
byte[] data = memStream.ToArray();
return data;
}

The way you had it, if any of the code in
// ...use writer
threw an exception, the file would not get closed... if you use the "using"
construction, it puts all the enclosed into a try/finally block for you, and
then calls Dispose() in the finally block, regardless of whether or not any
exceptions were thrown.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top