closing and disposing

  • Thread starter Thread starter keithv
  • Start date Start date
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
 
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.
 
Back
Top