Environment NewLine

August 3, 2006

If you are one of those people that put “\r\n” in your strings to indicate a newline, raise your right hand and smack your head.

Why?

1) You are assuming your code will always run on Windows. Unix uses \n alone, Apple (until OS 9) used \r alone. Your code might just end up being compiled under Mono and then what?
2) It looks plain ugly
3) You have to escape the characters again (at least in C# if you’re not using the verbatim operator @). This quickly becomes a pain in the — er –becomes cumbersome when dealing with a lot of text

What should you do?

Simple

string line = string.Format(“And this is the end of the line{0}”, Environment.NewLine);

kick it on DotNetKicks.com

3 Responses to “Environment NewLine”


  1. Good point. I also find it plain ugly. You can achieve the same in a StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.AppendLine(”And this is the end of the line”)

    Or the not-so-pretty version:

    string line = “And this is the end of the line” + Environment.NewLine


  2. [...] I just found a site (via dotnetkicks.com) that is advocating the use of Environment.NewLine. [...]


  3. I started using the String.Format(); method about a month ago (prior to that, I used the + for concatenation). Using Environment.Newline is much nicer.

    Need 2 linefeeds? sR = String.Format(”Hello World!{0}{0}”, Environment.Newline);


Leave a Reply