HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Extension method that writes to a stream

Submitted by: @import:stackexchange-codereview··
0
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 (change void to Stream) ?



  • Should I use the out keyword in before the Stream parameter ? 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 Dispose it ?



  • Should I pass StreamWriter instead of Stream ?

Solution

Your questions imply that you might not be quite aware of how streams or references work in C#.

  • You pass in a reference to a Stream



  • You create a StreamWriter which writes to that Stream



  • 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.