Search code examples
c#.netstreamdispose

Should I dispose a BinaryReader if I need to preserve the "wrapped" stream?


Both BinaryReader constructors require a stream parameter. If I need to keep the underlying stream as-is when I'm done with the BinaryReader, should I still call its Dispose()? If not, is there any other clean-up for the no longer needed BinaryReader?

I'm asking because I can't find a clear answer on MSDN page for BinaryReader.Dispose().

Small addtion

In my context I use the BinaryReader to read a couple of bytes, after which I set the position of the stream back to what it was before the BinaryReader was initialized.

Also, I'm using .Net 4.


Solution

  • No, it's fine to not dispose of the BinaryReader if you want to keep the stream open.

    I'd probably add a comment to explain what's going on though - and I'm not sure whether it's guaranteed that the BinaryReader will have only read from the stream as far as you've read from the BinaryReader... it might have read more into a buffer, for example. Obviously that's not a problem if you then seek on the stream.