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'.
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?