Raw string literals in C# provide a flexible way to work with multiline strings, with some interesting rules around how quotes work.
The key insight is that you can use any number of double quotes (three or more) to delimit your string, as long as the opening and closing sequences have the same number of quotes.
The Basic Rules
- You must use at least three double quotes (
""") to start and end a raw string literal
- The opening and closing quotes must have the same count
- The closing quotes must be on their own line for proper indentation
- If your string content contains a sequence of double quotes, you need to use more quotes in your delimiter than the longest sequence in your content
Examples with Different Quote Counts
// Three quotes - most common usage
string basic = """
This is a basic
multiline string
""";
// Four quotes - when your content has three quotes
string withThreeQuotes = """"
Here's some text with """quoted""" content
"""";
// Five quotes - when your content has four quotes
string withFourQuotes = """""
Here's text with """"nested"""" quotes
""""";
// Six quotes - for even more complex scenarios
string withFiveQuotes = """"""
Look at these """""nested""""" quotes!
"""""";
The N+1 Rule
The general rule is that if your string content contains N consecutive double quotes, you need to wrap the entire string with at least N+1 quotes. This ensures the compiler can properly distinguish between your content and the string's delimiters.
// Example demonstrating the N+1 rule
string example1 = """
No quotes inside
"""; // 3 quotes is fine
string example2 = """"
Contains """three quotes"""
""""; // Needs 4 quotes (3+1)
string example3 = """""
Has """"four quotes""""
"""""; // Needs 5 quotes (4+1)
Practical Tips
- Start with three quotes (
""") as your default
- Only increase the quote count when you actually need to embed quote sequences in your content
- The closing quotes must be on their own line and should line up with the indentation you want
- Any whitespace to the left of the closing quotes defines the baseline indentation
// Indentation example
string properlyIndented = """
{
"property": "value",
"nested": {
"deeper": "content"
}
}
"""; // This line's position determines the indentation
This flexibility with quote counts makes raw string literals extremely versatile, especially when dealing with content that itself contains quotes, like JSON, XML, or other structured text formats.
Walt is a computer scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.
Last updated on: