Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use an own class for Console.WriteLine override?

Tags:

c#

overriding

I want my ConsoleEngine class to handle the Console.WriteLine() Method. How do I have to prepare my ConsoleEngine class to override the WriteLine() method?

like image 437
SleepyNeko Avatar asked Sep 18 '15 21:09

SleepyNeko


1 Answers

You can create a class that derives from TextWriter:

public class MyWriter : TextWriter
{
    public override void Write(char value)
    {
        //Do something, like write to a file or something
    }

    public override void Write(string value)
    {
        //Do something, like write to a file or something
    }

    public override Encoding Encoding
    {
        get 
        {
            return Encoding.ASCII;
        }
    }
}

and set the Console output to an instance of that class:

Console.SetOut(new MyWriter());
like image 110
Dave Zych Avatar answered Oct 14 '22 15:10

Dave Zych