When inserting a new line character into a string I have usually done this:
str = "First line\nSecond line";
In C#, is this the standard practice? Should I also include the 'carriage return' character '\r'? Are there any difference between the following, and if so, what are they?
str = "First line\nSecond line"; str = "First line\r\nSecond line";
If using both 'carriage return' and 'line feed' is standard practice, is there a specific order and why?
Note: I read a few other posts on SO but didn't find an answer specific to .NET/C#.
Edit: After testing a little app, I didn't not see any difference between '\n' and '\n\r' or '\r\n'.
A line feed means moving one line forward. The code is \n . A carriage return means moving the cursor to the beginning of the line.
CRLF (but not CRNL) is used for the pair "\r\n". Form feed means advance downward to the next "page". It was commonly used as page separators, but now is also used as section separators. Text editors can use this character when you "insert a page break".
CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. LF = Line Feed ( \n , 0x0A in hexadecimal, 10 in decimal) — moves the cursor down to the next line without returning to the beginning of the line.
Carriage return by itself provided the ability to overprint the line with new text. This could be used to produce bold or accented characters, underscores, struck-out text, and some composite symbols. Early mechanical printers were too slow to return the carriage in the time it took to process one character.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With