How to create Multiline String in CSharp examples | C# Examples

Every language has a string literal to store a single-line string value. Sometimes, We want to declare a string to store string span in multiple lines.

Let’s see a string literal example

string str = "Welcome to my site";

Let’s create a multiline string

string s =
  "one line\n" +
  "second line \n" ;

The above syntax creates multi-line strings, but disadvantages due to the string being immutable. Many new strings are created and increase the heap size.

Let’s see how to declare a multi-line string in C# to avoid issues.

C# Multiline string literals examples

There are multiple ways we can declare multi-line string literals

  • using Raw String literal with triple-double quotes

Declare a string enclosed in triple quotes, and assign it to a string variable.

The advantage is No need of writing escape characters.

using System;

public class Program {
  public static void Main() {
    var message = """
    Single line 1.
    single line 2.
    """;
    Console.WriteLine(message);

  }
}

Another way using a verbatim string literal syntax

A string literal prefixed with@ makes the multi-line string, this is also called a verbatim string. verbatim strings are not escaped during processing

Advantage: escape characters are not processed.

using System;

public class Program {
  public static void Main() {

    var str = @ "Single line 1.
    Single line 1.
    single line 2.
    ";

    Console.WriteLine(str);

  }
}

Another way is Interpolated verbatim string.

variables are interpolated in a verbatim string by prefixing $. Variables values replaced runtime

Here is an example

using System;

public class Program {
  public static void Main() {
    string name = "john ";

    var str = $ @ "{name} Single line 1.
    Single line 2.
    single line 3.
    ";

    Console.WriteLine(str);

  }
}

Output:

john Single line 1.
    Single line 2.
    single line 3.

Third way usig StringBuilder

Since String is an immutable object, use StringBuilder to append strings.

The append method concatenates the string to the end of a string.

using System;
using System.Text;
public class Program {
  public static void Main() {
    var str = new StringBuilder();
    str.Append("line1\n");
    str.Append("line2 ");
    str.ToString();

    Console.WriteLine(str);

  }
}