C# Raw String Literal — Complete Guide
In this tutorial, you'll learn about C# Raw String Literal. We cover key concepts, practical examples, and best practices.
You need to embed JSON, XML, or a long SQL query in your C# code. You escape every quote, use \n for every newline, and the result is unreadable. Raw string literals (C# 11) let you write the content exactly as it appears.
Wrong
string json = "{\n \"name\": \"Alice\",\n \"age\": 30\n}";
Output: Works, but the string is unreadable. The escaped quotes and explicit newlines make it hard to edit.
Right
string json = """
{
"name": "Alice",
"age": 30
}
""";
Output: Same JSON, readable. The triple quotes """ delimit the string. Content between them is literal — no escaping needed.
Raw string literals also handle indentation:
string html = """
<div>
<p>Hello, World!</p>
</div>
""";
The closing """ determines the common indentation to strip.
For interpolation, use $ with multiple braces:
string name = "Alice";
string json = $$"""
{
"name": "{{name}}",
"age": 30
}
""";
// Produces: { "name": "Alice", "age": 30 }
Prevention
- Use
"""..."""for JSON, XML, HTML, SQL, and any embedded language. - Use
$$"""..."""when you need interpolation inside raw string literals. - Use
"""at the start and end — the compiler uses the count of"for delimiter detection. - Use consistent indentation — the closing
"""position determines the strip prefix. - Use raw string literals for test data with embedded strings or multi-line content.
- Avoid raw string literals for simple single-line strings — regular or verbatim strings are sufficient.
Common Mistakes with raw string literal
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Raw string literals are used in DodaTech for embedding test payloads and configuration templates. For more C#, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro