13

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
  """;
4
  • 5
    Because single quotes don't allow newline inside. This was a decision made long time ago, and cannot be changed now. That's why """ were introduced.
    – freakish
    Jan 27 at 9:14
  • 7
  • 1
    If I remember correctly, using triple double-quotes also allows you to align the start of each line in your multiline literal without introducing unwanted leading whitespace. I can't recall exactly how it worked but I saw a YouTube video on it a while back. Never used it myself so I can't provide details but that's something to consider. Jan 27 at 9:19
  • 2
    Multiline is just one aspect. This way allows to use just any text and throw it in as raw string without the need to apply additional escaping. Just use a series of quotes longer then the longest quote series in your raw string. Does not need to be 3 can be 5, 10, or even more.
    – Ralf
    Jan 27 at 9:20

2 Answers 2

19

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.

1
  • 1
    Reasons for downvote: the answer explains just a single use case (the OP did not ask for) but makes no mention to other use cases (see comments of question) or to any documentation at all; second half deals with a goal only implicitly mentioned. And as there is, again, no reference to any documentation, it looks like the exploitation of a side effect, presented in "And voila!" style. Additionally, my way addressing a goal like yours would be to replace all whitespace (outside quotes) with a single blank, which is a much more reliable solution, can be done via regex or with iterative approaches
    – syck
    Feb 2 at 15:44
6

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.