Carriage return and Line feed... Are both required in C#?
A carriage return \r
moves the cursor to the beginning of the current line. A newline \n
causes a drop to the next line and possibly the beginning of the next line; That's the platform dependent part that Alexei notes above (on a *nix system \n
gives you both a carriage return and a newline, in windows it doesn't)
What you use depends on what you're trying to do. If I wanted to make a little spinning thing on a console I would do str = "|\r/\r-\r\\\r";
for example.
System.Environment.NewLine
is the constant you are looking for - http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx which will provide environment specific combination that most programs on given OS will consider "next line of text".
In practice most of the text tools treat all variations that include \n
as "new line" and you can just use it in your text "foo\nbar"
. Especially if you are trying to construct multi-line format strings like $"V1 = {value1}\nV2 = {value2}\n"
. If you are building text with string concatenation consider using NewLine
. In any case make sure tools you are using understand output the way you want and you may need for example always use \r\n
irrespective of platform if editor of your choice can't correctly open files otherwise.
Note that WriteLine
methods use NewLine
so if you plan to write text with one these methods avoid using just \n
as resulting text may contain mix of \r\n
and just \n
which may confuse some tools and definitely does not look neat.
For historical background see Difference between \n and \r?