Why does "\n" give a new line on Windows?
I am late to the party by many years. However, https://en.wikipedia.org/wiki/Newline has very good explanation of how NEWLINE escape sequences work in the context of programming languages and text/binary outputs.
It comes down to this - most programming languages translate "\n" into native platform's NEWLINE sequence while writing text. And, translate native platform's NEWLINE sequence into "\n" while reading text.
'\n'
is the Line Feed character. Traditionally, it caused the printer to roll the paper up one line. '\r'
is the Carriage Return character, which traditionally caused the printer head to move to the far left edge of the paper.
On printers and consoles that interpret the characters in this manner, the output of line1\nline2
would be
line1
line2
Many consoles (and editors) will interpret '\n' to mean that you want to start a new line and position the cursor at the beginning of that new line. That is what you see here.
You should use Environment.NewLine rather than hard-coding any particular constants.
This is just the standard behaviour of the underlying Windows console. A native C app will do exactly the same if you output 0x0A
to the console.
Of course, you should be using Environment.NewLine
for your new lines. Environment.NewLine
resolves to \r\n
on Windows and \n
on Unix like systems.
File encodings != Console
interpretation.
In other words, while the "Windows Standard" of CR
+ LF
exists for files, just the LF
, or \n
has resulted in the appropriate carriage return and new line interpretation in console windows.