Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# triple double quotes (three double quotes)

Tags:

string

c#

format

What is the purpose of triple douple quotes """ in C#? It seems it is used for multiline text. But why not use single double quotes with @"..."?

string text = """
  some text
  some text
  some text
  """;
like image 383
Andrei Avatar asked Sep 02 '25 01:09

Andrei


1 Answers

Source: C# 11 Preview Updates – Raw string literals

If you work with strings literal that contain quotes or embedded language strings like JSON, XML, HTML, SQL, Regex and others, raw literal strings may be your favorite feature of C# 11. Previously if you copied a literal string with quotes into a C# literal, the string ended at the first double quote with compiler errors until you escaped each one. Similarly, if you copied text with curly braces into an interpolated string literal, each curly bracket was interpreted as the beginning of a nested code expression unless you escape it, generally by doubling the curly bracket.

Raw string literals have no escaping. For example, a backslash is output as a backslash, and \t is output as the backslash and a t, not as the tab character.

Raw string literals start and end with at least three double quotes ("""..."""). Within these double quotes, single " are considered content and included in the string. Any number of double quotes less than the number that opened the raw string literal are treated as content. So, in the common case of three double quotes opening the raw string literals, two double quotes appearing together would just be content. If you need to output a sequence of three or more double quotes, just open and close the raw string literal with at least one more quote than that sequence.

Raw string literals can be interpolated by preceding them with a $. The number of $ that prefixes the string is the number of curly brackets that are required to indicate a nested code expression. This means that a $ behaves like the existing string interpolation – a single set of curly brackets indicate nested code. If a raw string literal is prefixed with $$, a single curly bracket is treated as content and it takes two curly brackets to indicate nested code. Just like with quotes, you can add more $ to allow more curly brackets to be treated as content. For example:

const int veryCold = -30;
const int comfortable = 20;

string jsonString =
  $$"""
  {
    "TemperatureRanges": {
      "Cold": {
        "High": {{comfortable}},
        "Low": {{veryCold}}
      }
    }
  }
  """;

Raw string literals also have new behavior around automatically determining indentation of the content based on leading whitespace. To learn more about this and to see more examples on this feature, check out the docs article Raw String Literals.

P.S. Thanks to Roe and ProgrammingLlama for pointing to this articles.

like image 55
Andrei Avatar answered Sep 07 '25 18:09

Andrei