Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : Manually creating a console.writeline

Tags:

methods

c#

class

I am trying to simulate the Console.Writeline manually. i.e : i am creating a small Console Class with function WriteLine. See my code below :

static class Console
{
    public static string WriteLine(string text)
    {
        return text;
    }
}

So i tried that with :

class Program
{
    static void Main()
    {
        Console.WriteLine("HiMan");
    }
}
static class Console
{
    public static string WriteLine(string text)
    {
        return text;
    }
}

I know that it returns the text , but how can i display it on the screen without using the Write or Writeline methods ?

I am creating this example to make people understand how classes work and why when i use WriteLine or Write() it displays the text in the console window.

like image 207
BOSS Avatar asked Oct 23 '25 06:10

BOSS


2 Answers

It depends on how deep you want to go. Console.WriteLine() calls WriteLine on Console.Out internally. Console.Out is a TextWriter that provides the WriteLine implementation. You can always implement your own WriteLine by writing bytes to the stream directly.

If you want to go deeper, such as writing to the console buffer directly, be aware that the Out, In and Error properties of Console are all redirectable and ignoring them may lead to issues, such as not being able to redirect input and output using pipes on the command line.

like image 167
akton Avatar answered Oct 24 '25 19:10

akton


I'm guessing you want to do this on a fairly low level. I've used ReadConsoleOutput and WriteConsoleOutput to directly read and write the Console's display in ways that Console.WriteLine wouldn't let me (these are great for retro 2d console games, my original intent).

PInvoke links: ReadConsoleOutput | WriteConsoleOutput

You may not need the ReadConsoleOutput, but for those that Google this page, these methods sort of go hand in hand with each other.

If you want to read from the keyboard, I believe you can use ReadConsoleInput but I haven't actually tried that. Small grain of salt on that advice.

like image 33
Corey Ogburn Avatar answered Oct 24 '25 19:10

Corey Ogburn