Reputation: 897
From my understanding it seems logical that the buffer parameter of Stream.Read(byte[] buffer, int offset, int count)
should be an out parameter as the value is read into the buffer that passed in, but that is not the case.
What is the reason for this? Is there something I am overlooking?
Upvotes: 2
Views: 341
Reputation: 16991
out
is only used when the instance is assigned from within the method, and passed back out. Stream.Read
expects the buffer to have already been created by the programmer before calling the method. The existing instance is just being passed in, where the data within the instance is being modified, not the reference its self.
While out
allows you to pass in an existing instance, it guarantees that a different instance will be coming back out. In-fact, even though it allows you to pass in an existing instance, you can't access its value from within the method. It treats the parameter as if it were never assigned. "CS0269 Use of unassigned out parameter 'value'"
You will get a compiler error if you don't assign something to the parameter before the method returns. "CS0177 The out parameter 'value' must be assigned to before control leaves the current method"
Upvotes: 4
Reputation: 726779
Making buffer
an out
parameter would make the API less usable, without offering any improvement in return.
Currently, a reference for the buffer is passed to the method (because arrays are reference types), and the output is written directly into the array.
Using out
would prevent important use cases, when the buffer is external to the caller of Stream.Read
- for example, a read-only property of some of the classes that it uses.
Moreover, there would not be much improvement in usability, because swapping the buffer from under the caller, presumably, to expand it, is not an appropriate course of action when offset
and count
are passed to you by the caller.
Upvotes: 1
Reputation: 1579
the data read is put into an already specified array of bytes. buffer
in this situation is already instantiated by the calling code and may have non-zero bytes in the array already. if it was specified as out
then the Read method would be creating a buffer, and returning it back. In that situation offset
and count
would be redundant, as it's made the byte array based on its own findings, it doesn't need to know where to "fit in" its data being read.
Upvotes: 1