Raw string literals are a powerful feature introduced in C# 11 that simplify the way we handle strings, especially those containing special characters or spanning multiple lines.
What are raw string literals?
A raw string literal starts and ends with a minimum of three double-quote characters ("""
). This allows you to include characters like backslashes (\
), single quotes ('
), and double quotes ("
) without needing to escape them.
Here's a simple example:
The above example is a single line string literal. But the feature really shines when using raw string literals to span multiple lines. This is particularly useful for embedding large blocks of text, such as XML or JSON, directly into your code.
Remark: It is very important to check the documentation as some very specific rules are applicable when using multiline string literals.
I stumbled over this myself when I added a JSON schema description inside a piece of code:
The compiler complained and returned the following error message:
CS8999 - Line does not start with the same whitespace as the closing line of the raw string literal.
Spacing is really important when using raw string literals. The embedded text should at least be the same indentation level as the starting/ending quotes: