user2957282 user2957282 - 2 months ago 20
C# Question

C# Decorating Console class

I came across an assignment to decorate a Console class (in C#), and implement some custom things inside Write and WriteLine methods.

I had no problem with decorating streams to provide additional functionality, but I have no idea, how to decorate a Console, mostly because of it's static (and have no inheritance, only from System.Object).

So what are the possibilities here?

Thank you!
Lukas

Answer

You can replace the streams Console writes and reads to using the Console.SetOut(TextWriter), Console.SetIn(TextReader), and Console.SetError(TextWriter). Just create custom TextWriter or TextReader classes that does your decorator behavior and assign them to the static methods.

public static void Main()
{
    TextWriter oldOut = Console.Out;
    TextWriter decorator = new MyCustomDecorator(oldOut);
    Console.SetOut(decorator);

    //Do stuff;
}