[c#] How to insert newline in string literal?

In .NET I can provide both \r or \n string literals, but there is a way to insert something like "new line" special character like Environment.NewLine static property?

This question is related to c# .net line-breaks

The answer is


If you are working with Web application you can try this.

StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />")

If you really want the New Line string as a constant, then you can do this:

public readonly string myVar = Environment.NewLine;

The user of the readonly keyword in C# means that this variable can only be assigned to once. You can find the documentation on it here. It allows the declaration of a constant variable whose value isn't known until execution time.


One more way of convenient placement of Environment.NewLine in format string. The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine

Usage

   " X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
   gives:
    X=1
    Y=2
    X+Y=3

Code

    ///<summary>
    /// Use "string".FormatIt(...) instead of string.Format("string, ...)
    /// Use {nl} in text to insert Environment.NewLine 
    ///</summary>
    ///<exception cref="ArgumentNullException">If format is null</exception>
    [StringFormatMethod("format")]
    public static string FormatIt(this string format, params object[] args)
    {
        if (format == null) throw new ArgumentNullException("format");

        return string.Format(format.Replace("{nl}", Environment.NewLine), args);
    }

Note

  1. If you want ReSharper to highlight your parameters, add attribute to the method above

    [StringFormatMethod("format")]

  2. This implementation is obviously less efficient than just String.Format

  3. Maybe one, who interested in this question would be interested in the next question too: Named string formatting in C#


Here, Environment.NewLine doesn't worked.

I put a "<br/>" in a string and worked.

Ex:

ltrYourLiteral.Text = "First line.<br/>Second Line.";


string myText =
    @"<div class=""firstLine""></div>
      <div class=""secondLine""></div>
      <div class=""thirdLine""></div>";

that's not it:

string myText =
@"<div class=\"firstLine\"></div>
  <div class=\"secondLine\"></div>
  <div class=\"thirdLine\"></div>";

If you want a const string that contains Environment.NewLine in it you can do something like this:

const string stringWithNewLine =
@"first line
second line
third line";

EDIT

Since this is in a const string it is done in compile time therefore it is the compiler's interpretation of a newline. I can't seem to find a reference explaining this behavior but, I can prove it works as intended. I compiled this code on both Windows and Ubuntu (with Mono) then disassembled and these are the results:

Disassemble on Windows Disassemble on Ubuntu

As you can see, in Windows newlines are interpreted as \r\n and on Ubuntu as \n


If I understand the question: Couple "\r\n" to get that new line below in a textbox. My example worked -

   string s1 = comboBox1.Text;     // s1 is the variable assigned to box 1, etc.
   string s2 = comboBox2.Text;

   string both = s1 + "\r\n" + s2;
   textBox1.Text = both;

A typical answer could be s1 s2 in the text box using defined type style.


I like more the "pythonic way"

List<string> lines = new List<string> {
    "line1",
    "line2",
    String.Format("{0} - {1} | {2}", 
        someVar,
        othervar, 
        thirdVar
    )
};

if(foo)
    lines.Add("line3");

return String.Join(Environment.NewLine, lines);

static class MyClass
{
   public const string NewLine="\n";
}

string x = "first line" + MyClass.NewLine + "second line"

var sb = new StringBuilder();
sb.Append(first);
sb.AppendLine(); // which is equal to Append(Environment.NewLine);
sb.Append(second);
return sb.ToString();

newer .net versions allow you to use $ in front of the literal which allows you to use variables inside like follows:

var x = $"Line 1{Environment.NewLine}Line 2{Environment.NewLine}Line 3";

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to line-breaks

HTML5 tag for horizontal line break Split string in JavaScript and detect line break Match linebreaks - \n or \r\n? How to linebreak an svg text within javascript? What is the difference between a "line feed" and a "carriage return"? Bash: Strip trailing linebreak from output How to read a file without newlines? How to break lines in PowerShell? How do I specify new lines on Python, when writing on files? How to remove line breaks (no characters!) from the string?