patterncsharpMinor
Extension method that writes to a stream
Viewed 0 times
streamwritesmethodextensionthat
Problem
public static void streamReport(this Report report, Stream stream)
{
using (var streamWriter = new StreamWriter(stream))
{
//some logic that calls streamWrite.Write()
streamWriter.Flush();
}
//Should "return stream;" here ?
}I am writing an extension method to an object in which I would like to transform to a CSV which is generated and returned to a client (web).
My questions are:
- Should I return
stream(changevoidtoStream) ?
- Should I use the
outkeyword in before theStreamparameter ? Is this a common way to let the caller know the parameter will be changed ?
- Should I change the method to generate a new stream (and not accept one) and trust the user to
Disposeit ?
- Should I pass
StreamWriterinstead ofStream?
Solution
Your questions imply that you might not be quite aware of how streams or references work in C#.
Therefor there is no need to try and return the
However there is a catch in your implementation: disposing the
- You pass in a reference to a
Stream
- You create a
StreamWriterwhich writes to thatStream
- This will automatically make changes visible to anyone holding a reference to the same
Stream.
Therefor there is no need to try and return the
Stream in any way from the method to make the changes visible to the caller - you just need to write to it. This is at least how I interpret your questions.However there is a catch in your implementation: disposing the
StreamWriter will automatically close the underlying Stream which I find hugely annoying at times. Only since .NET 4.5 there is a constructor for StreamWriter which allows you to leave the Stream open. So right now your extension method will close the Stream which I guess is not the intention. Your only option to avoid that is to use .NET 4.5 or do not wrap the StreamWriter in a using statement.Context
StackExchange Code Review Q#41939, answer score: 8
Revisions (0)
No revisions yet.