1

As the heading implies, would I be best to use \n, \r\n or System.Environment.NewLine for line breaks in my C# applications?

I have a console, WinForms and WPF app which at present all use \n (where required), but in my console app I have found that when redirecting output from the CLi and open the output in Notepad the line breaks are not correctly recognised. I could just alter my behaviour for this one app but I am seeking the advice of those who consistently use a particular method and why.

Cheers!

Update:

So the general consensus is that use System.Environment.NewLine unless a specific requirement arises which needs \n (Unix/OS X), \r (OS 9) or \r\n (Windows)

Thanks all and sorry about the dup!

SmithPlatts
  • 773
  • 7
  • 20
  • It depends on which platform do you plan to re-read your writes. However, unless specific requirements I would always go for Environment.NewLine – Steve Dec 15 '13 at 08:54
  • Good read about difference [here](http://www.dotnetperls.com/newline), – Rohit Vats Dec 15 '13 at 08:55
  • @OndrejJanacek I did search both SO and Google, but must have somehow skimmed or just plain missed it; I cannot believe I missed something so bleeding obvious :( – SmithPlatts Dec 15 '13 at 13:09
  • @Steve cheers fro the succinct comment :) – SmithPlatts Dec 15 '13 at 13:09
  • 1
    @RohitVats that's a good explanation of a few different bits; cheers! – SmithPlatts Dec 15 '13 at 13:10
  • @SmithPlatts Sometimes I got an answer on my question in the moment I start writing a question here on SO and it shows me similar questions already asked. – Ondrej Janacek Dec 15 '13 at 13:10
  • @OndrejJanacek I have had that too before, but in this case not :/ (I always make a point to check the suggestions before even writing the question) – SmithPlatts Dec 15 '13 at 13:18

2 Answers2

8

Better use Environment.NewLine because \r and \n are platform dependant.

\n is Unix, \r is Mac, \r\n is Windows

Environment.NewLine would return any of the above based on the operating system.

Kurubaran
  • 8,696
  • 5
  • 43
  • 65
1

It will always, unless you're intentionally writing a 'foreign' file, be best to use Environment.NewLine - that's what it's there for. As you've discovered, sometime you can get away with other things, sometimes you can't.

It's very easy to write code which reads text files so that it doesn't really care what combination of \n and \r are used to end lines, but as you've discovered, Notepad is strict on this.

Will Dean
  • 39,055
  • 11
  • 90
  • 118
  • It all came from a complete ignorance where by I did not actually know about `NewLine` until today :/ (still somewhat newish to .NET from other languages); cheers for the answer! – SmithPlatts Dec 15 '13 at 13:16