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();
}
A
StreamWriter
is aTextWriter
. TheWrite*
static methods ofConsole
write toConsole.Out
.Console.Out
is aTextWriter
. So the common "thing" is writing on aTextWriter
.You can use the
WriteToFile
/WriteToConsole
methods (or directly thePrintWindow
method, that I would rename to something more apt, likeWriteToTextWriter
)