Implementing Write(char)
on your TextWriter
derived class is all you need to do. If somebody calls WriteLine
on your new class, the base class WriteLine
method is called. It will do the right thing: call your Write
method with the individual \r
and \n
characters.
Actually, WriteLine(string)
looks something like this:
void WriteLine(string s)
{
Write(s);
Write("\r\n");
}
And Write(string)
is, in effect:
foreach (char c in s)
{
Write(c);
}
All of the Write
methods in TextWriter
resolve to something that calls Write(char)
in a loop.
You really don't have to implement anything else. Just override Write(char)
and plug it in. It will work.
You can override those other methods. Doing so will make your class a little more efficient (faster). But it's not required. I say do the simplest thing you can. Then, if you determine after profiling that your custom writer is too slow, override other methods as necessary.
Here's a minimal TextWriter
descendant:
public class ConsoleTextWriter: TextWriter
{
public override void Write(char value)
{
Console.Write(value);
}
public override Encoding Encoding
{
get { return Encoding.Default; }
}
}
If I then write:
using (var myWriter = new ConsoleTextWriter())
{
myWriter.Write("hello, world");
myWriter.WriteLine();
myWriter.WriteLine();
myWriter.WriteLine("Goodbye cruel world.");
myWriter.Write("Fee fie foe foo!");
}
The output is:
hello, world
Goodbye cruel world.
Fee fie foe foo!