In this example from MS, you'll notice that after we read a byte from memory stream, it goes into an int which must then be converted to byte. It stikes me as strange that a function like .ReadByte()
doesn't return a byte in the first place. Is there a reason why MS did it this way?
// Read the remaining bytes, byte by byte.
while(count < memStream.Length)
{
byteArray[count++] =
Convert.ToByte(memStream.ReadByte());
}
a thought occured to me. Perhaps this comes down to usage. Perhaps ReadByte()
is often used to retrieve short lengths, which subsequents get consumed in the retrieve via length variety
int length=ms.ReadByte();
ms.Read(buf,0,lenth);
i.e. you can use the length without a cast. Is this a good enough reason?
This is not specific to Memory stream, rather it is because of the design of base class "Stream" and the reason for that is
Return value:
The unsigned byte cast to an Int32, or -1 if at the end of the stream.
-1 cannot be represented using unsigned byte