Home > Software engineering >  C# triple double quotes (three double quotes)
C# triple double quotes (three double quotes)

Time:01-30

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

string text = """
  some text
  some text
  some text
  """;

CodePudding user response:

I think a simple example can explain better than many a text. Suppose we have a sql query which we want to keep in a good format to be easy readable.

If we put it naive, it won't compile:

string sql = 
  "select id, 
          name
     from MyTable"; // <- Doesn't compile 

We can use @ to have verbatim strings which now compiles

string sql = 
 @"select id, 
          name
     from MyTable"; 

...

// A little bit different format somewhere else in c# code
string sameSql = @"select id, 
                          name
                     from MyTable"; 

But yet another problem arises: we have different strings and that's why RDBMS will treat them as different queries, both versions will be parsed and optimized, put into cache etc. So we have the same job done several times (and even worse: parsed queries cache can be flooded by same query in different formats and it'll be not enough space for other queries).

From sql we have

select id, 
          name
     from MyTable

From sameSql we have the same query but in a different format:

select id, 
                          name
                     from MyTable

Note that leading spaces are preserved (we used verbatim strings, right?) and that's a problem.

The solution is to use new """ construction

string sql = 
 """
    select id, 
           name
      from MyTable
 """; 

...

// A little bit different format
string sameSql = """
                    select id, 
                           name
                      from MyTable
                 """; 

In both cases we'll get the same text

select id, 
       name
  from MyTable

the query will be parsed, optimized and put into cache just once, c# code style ignored.

CodePudding user response:

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.

  • Related