Inheriting from BinaryReader

  • Thread starter Thread starter John Jeffery
  • Start date Start date
J

John Jeffery

Is there some way for a class which inherits from BinaryReader to access the
internal buffer of the BinaryReader class?

I was looking into the possibility of creating a specialization of the
BinaryReader class. What I had in mind was something like this:

public class MyBinaryReader : BinaryReader {

public SomeClass ReadSomeClass() {
// ...implementation here...
}

}

The BinaryReader class has a protected method called FillBuffer(numBytes),
which allows me to read exactly numBytes from the stream into an internal
buffer, but there appears to be no way to access the bytes just read by the
FillBuffer method.

Am I missing some obvious way to access the internal buffer?

I realise that I could use the ReadBytes() method but that presents me with
two problems:

(1) I would prefer not to have to create lots an lots of byte[] arrays which
are only going to be used for a short time and then have to be reaped by the
GC

(2) From my reading of the spec, the ReadBytes() method might return me
fewer bytes than I asked for. FillBuffer() already does the work of reading
the exact number of bytes (and throwing an EndOfStream exception if it
can't). I was hoping not to have to duplicate this effort.
 
"John Jeffery" <[email protected]> expressed in the message known
far and wide by the name thusly:
Is there some way for a class which inherits from BinaryReader to
access the internal buffer of the BinaryReader class?

Hi John,

Unfortunately, it doesn't look like you can do what you want this way...

What is your stream type that you are reading? Perhaps you can subclass the
stream instead, since it seems that BinaryReader is just calling Read (or
BeginRead/EndRead) on the stream to fill that buffer...

-rory 8)
 
Rory said:
Unfortunately, it doesn't look like you can do what you want this way...

What is your stream type that you are reading? Perhaps you can subclass the
stream instead, since it seems that BinaryReader is just calling Read (or
BeginRead/EndRead) on the stream to fill that buffer...

Thanks Rory, that is exactly how I got around my problem -- I subclassed a
stream and got my reader to use the stream. It's just that the job would
have been easier with access to the BinaryReader's buffer.

I guess my question to the Microsoft API guys (if any are reading this) is
why provide the BinaryReader.FillBuffer method to derived classes, but not
provide access to the buffer it fills? Is there some principle of API
design/security/whatever I am missing here, or is it an omission which
should be provided in a future release of .NET?
 
Back
Top