I have always wondered what the best practice for using a Stream
class in C# .Net is. Is it better to provide a stream that has been written to, or be provided one?
i.e:
public Stream DoStuff(...)
{
var retStream = new MemoryStream();
//Write to retStream
return retStream;
}
as opposed to;
public void DoStuff(Stream myStream, ...)
{
//write to myStream directly
}
I have always used the former example for sake of lifecycle control, but I have this feeling that it a poor way of "streaming" with Stream
's for lack of a better word.
I would prefer "the second way" (operate on a provided stream) since it has a few distinct advantages:
Stream
provided).Stream
extension method now or later.Also, if you're returning a new stream (option 1), it would feel a bit strange that you would have to Seek
again first in order to be able to read from it (unless you do that in the method itself, which is suboptimal once more since it might not always be required - the stream might not be read from afterwards in all cases). Having to Seek
after passing an already existing stream to a method that clearly writes to the stream does not seem so awkward.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With