3

I'm interested in how calling Console.WriteLine() actually displays text.

I've had a look at the source code from: http://referencesource.microsoft.com/#mscorlib/system/io/textwriter.cs,5f99350fdf8dae53 and can see that this method from TextWriter ends up getting called:

        // Writes a character to the text stream. This default method is empty,
        // but descendant classes can override the method to provide the
        // appropriate functionality.
        //
        public virtual void Write(char value) {
        }

What is the descendant class that overrides this method? And what is the implementation?

7

Check out the source from the CoreCLR branch, which Microsoft are hosting on github:

    [SecuritySafeCritical]
    static Console()
    {
        _outputHandle = new SafeFileHandle(Win32Native.GetStdHandle(Win32Native.STD_OUTPUT_HANDLE), false);
    }

    [SecuritySafeCritical]
    public static unsafe void Write(string s)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(s);
        fixed (byte * pBytes = bytes)
        {
            int bytesWritten;
            Win32Native.WriteFile(_outputHandle, pBytes, bytes.Length, out bytesWritten, IntPtr.Zero);
        }
    }

There are two things going on here: in the static ctor, the code is getting a Win32 handle to the STD_OUTPUT virtual file, which wraps the standard output to the process's attached console. And in the Write method, it's writing the data to that file.

Basically, it wraps the internal OS facilities for writing to a console, which is virtual file.

  • How did you find that? And why can't you navigate there if you start off at one of the Console.WriteLine() overloaded methods? – Backwards_Dave Jun 3 '16 at 9:19
  • 1
    @Backwards_Dave: Unless you use a tool like DotPeek or connect to Microsoft's symbol servers, or find a way to set the github source as your symbol server, there's no source for your IDE to look at, so it doesn't. If you set that up, it can. – Magus Jun 6 '16 at 22:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.