Create a Generic method that will write to a file or write to console output

634 Views Asked by At

I have two functions that are identical in body, one writes to a file and one writes to the console.
Is there a way to make the File/Console generic to what I pass to the function?

public void WatchWindow()
{

    var max = _colLengths.Max();
    for (var rowIndex = 0; rowIndex < max; ++rowIndex)
    {
        for (var colIndex = 0; colIndex < WindowWidth; ++colIndex)
        {
            if (rowIndex < _colLengths[colIndex])
                Console.Write("{0} ", _actualWindow[colIndex]rowIndex].SymbolName);
            else
                Console.Write("   ");
         }
         Console.WriteLine();
     }
     Console.WriteLine();
}

public void PrintWindow(StreamWriter file)
{

    var max = _colLengths.Max();
    for (var rowIndex = 0; rowIndex < max; ++rowIndex)
    {
        for (var colIndex = 0; colIndex < WindowWidth; ++colIndex)
        {
             if (rowIndex < _colLengths[colIndex])
                 file.Write("{0} ", _actualWindow[colIndex][rowIndex].SymbolName);
             else
                 file.Write("   ");
         }
         file.WriteLine();
     }
     file.WriteLine();
}
1

There are 1 best solutions below

0
On

A StreamWriter is a TextWriter. The Write* static methods of Console write to Console.Out. Console.Out is a TextWriter. So the common "thing" is writing on a TextWriter.

public void WriteToFile(StreamWriter file)
{
    PrintWindow(file);
}

public void WriteToConsole()
{
    PrintWindow(Console.Out);
}

public void PrintWindow(TextWriter writer)
{

    var max = _colLengths.Max();
    for (var rowIndex = 0; rowIndex < max; ++rowIndex)
    {
        for (var colIndex = 0; colIndex < WindowWidth; ++colIndex)
        {
            if (rowIndex < _colLengths[colIndex])
                writer.Write("{0} ", _actualWindow[colIndex][rowIndex].SymbolName);
            else
                writer.Write("   ");
        }
        writer.WriteLine();
    }
    writer.WriteLine();
}

You can use the WriteToFile/WriteToConsole methods (or directly the PrintWindow method, that I would rename to something more apt, like WriteToTextWriter)