tags:

views:

34

answers:

2

I want to write a function that accepts a stream argument. Ideally I would like that argument to be the console (if I want the output to go to the screen), or a file (if I want to save the output).

Something like this:

void myFunc(<some stream object> strm)
{
   strm.Write("something");
}

How do I declare and call the function to get the behavior I am looking for?

+3  A: 

Instead of Stream, consider using TextWriter. That way, you can use a StreamWriter for writing to files, and Console.Out for writing to the console:

static void DoStuff(TextWriter output)
{
    output.WriteLine("doing stuff");
}

static void Main()
{
    DoStuff(Console.Out);

    using( var sw = new StreamWriter("file.txt") )
    {
        DoStuff(sw);
    }
}
Mark
Yes, since the question implies Text based data this would be my choice too.
Henk Holterman
A: 

I entirely agree with Mark's answer: a TextWriter is almost certainly the way to go.

However, if you absolutely have to cope with an arbitrary stream, you can use Console.OpenStandardOutput() to get a stream to the console. I would strongly advise you not to use this unless you really have to though.

Jon Skeet