0
0
CsharpConceptBeginner · 3 min read

Raw String Literal in C#: What It Is and How to Use It

A raw string literal in C# is a way to write strings exactly as they appear, including line breaks and special characters, without needing escape sequences. It uses triple double quotes """ to start and end the string, making it easier to write multi-line text or code snippets.
⚙️

How It Works

Raw string literals let you write text exactly as you want it to appear, including new lines, quotes, and backslashes, without adding extra escape characters. Imagine writing a letter where you want every line and symbol to stay just as you typed it, without any changes or special codes.

In C#, you start and end a raw string literal with three double quotes """. Everything inside these quotes is taken literally, so you don't need to use backslashes to escape characters like quotes or new lines. This makes it very handy for writing code snippets, JSON, XML, or any text that has many special characters or spans multiple lines.

💻

Example

This example shows a raw string literal containing multiple lines and quotes without escape characters.

csharp
string rawText = """
Hello, "friend"!
This is a raw string literal.
It preserves line breaks and "quotes" exactly.
""";

Console.WriteLine(rawText);
Output
Hello, "friend"! This is a raw string literal. It preserves line breaks and "quotes" exactly.
🎯

When to Use

Use raw string literals when you need to include text with many special characters like quotes, backslashes, or new lines, and you want to avoid cluttering your code with escape sequences. They are perfect for embedding JSON, XML, SQL queries, or multi-line messages directly in your code.

For example, if you want to include a block of HTML or a multi-line error message, raw string literals keep your code clean and easy to read.

Key Points

  • Raw string literals start and end with triple double quotes """.
  • They preserve all characters exactly, including new lines and quotes.
  • No need to escape special characters inside raw string literals.
  • Introduced in C# 11 to simplify multi-line and complex strings.

Key Takeaways

Raw string literals use triple quotes to write strings exactly as typed.
They make multi-line and special character strings easier to read and write.
No escape sequences are needed inside raw string literals.
Ideal for embedding code snippets, JSON, XML, or multi-line text.
Raw string literals were introduced in C# 11.