Question

Multiline String Literals in C#: Verbatim and Raw String Syntax

csharpstringshorthand

Question

Is there a simple way to create a multiline string literal in C#?

For example, I currently have code like this:

string query = "SELECT foo, bar"
    + " FROM table"
    + " WHERE id = 42";

I know that PHP supports heredoc-style syntax such as:

<<<BLOCK
...
BLOCK;

Does C# provide something similar for writing multiline strings more easily?

Short Answer

By the end of this page, you will understand how C# handles multiline string literals, when to use verbatim strings and raw string literals, and how they compare to concatenating normal strings. You will also see practical examples for SQL, JSON, file paths, and formatted text.

Concept

In C#, a string literal is text written directly in your code. A multiline string literal lets you write text across multiple lines without manually joining many separate strings.

This matters because many real programs need to store or build readable blocks of text, such as:

  • SQL queries
  • JSON samples
  • XML
  • Email templates
  • File content
  • Multi-line messages

Without multiline string support, code can become hard to read:

string query = "SELECT foo, bar" +
               " FROM table" +
               " WHERE id = 42";

C# supports better options.

1. Verbatim string literals

A verbatim string starts with @:

string query = @"SELECT foo, bar
FROM table
WHERE id = 42";

This preserves line breaks and treats backslashes literally, which is very useful for paths and formatted text.

2. Raw string literals

In newer versions of C#, you can use raw string literals with triple quotes:

string query = """
SELECT foo, bar
FROM table
WHERE id = 42
""";

This is often the cleanest option, especially when the text contains quotes.

Why this matters

Readable strings make code easier to maintain. If a SQL query or JSON document looks in code the same way it will appear at runtime, debugging and editing become much easier.

Mental Model

Think of a normal string as writing a sentence on one sticky note. If the sentence gets too long, you have to tape several sticky notes together.

A multiline string literal is like using a full sheet of paper instead. You can write the text naturally across multiple lines, and C# keeps that structure for you.

  • Normal string: many small pieces joined together
  • Multiline string: one block of text written as it should appear
  • Verbatim/raw string: "what you type is mostly what you get"
Take Quiz

Syntax and Examples

Normal string concatenation

string query = "SELECT foo, bar " +
               "FROM table " +
               "WHERE id = 42";

This works, but it becomes messy for longer text.

Verbatim string literal with @

string query = @"SELECT foo, bar
FROM table
WHERE id = 42";

Notes

  • Line breaks are preserved.
  • Backslashes do not need escaping.
  • To include a double quote inside a verbatim string, use "".

Example:

string message = @"She said, ""Hello"" to everyone.
Then she left.";

Raw string literal with """

string query = """
SELECT foo, bar
FROM table
WHERE id = 42
""";

Why raw strings are useful

  • Easy to read
  • Great for multiline text
  • Quotes usually do not need escaping
  • Especially useful for JSON, SQL, and templates

Example:

string json = """
{
  "name": "Alice",
  "age": 30
}
""";

File path example

Verbatim strings are also commonly used for Windows paths:

string path = @"C:\Users\Sam\Documents";

Actually, with a verbatim string, the backslashes are literal, so this can be simplified to:

string path = @"C:\Users\Sam\Documents";

A cleaner correct form is:

```csharp
string path = @"C:\Users\Sam\Documents";

The intended idea is that with `@`, you usually write paths more naturally, for example:

```csharp
string path = @"C:\Temp";

More practically, compare:

```csharp
string normalPath = "C:\\Temp\\file.txt";
string verbatimPath = @"C:\Temp\file.txt";

The verbatim version is easier to read.

Step by Step Execution

Consider this example:

string query = @"SELECT foo, bar
FROM table
WHERE id = 42";

Console.WriteLine(query);

Step by step

  1. C# sees the @ before the opening quote.
  2. That tells C# this is a verbatim string literal.
  3. Everything inside the quotes is stored as text, including line breaks.
  4. The value assigned to query becomes:
SELECT foo, bar
FROM table
WHERE id = 42
  1. Console.WriteLine(query); prints the string exactly with those line breaks.

Output

SELECT foo, bar
FROM table
WHERE id = 42

Now compare with concatenation:

string query = "SELECT foo, bar" +
               " FROM table" +
               " WHERE id = 42";

Here, C# joins three string values into one single line:

SELECT foo, bar FROM table WHERE id = 42

That means concatenation does not automatically create line breaks unless you explicitly add them:

string query = "SELECT foo, bar\n" +
               "FROM table\n" +
               "WHERE id = 42";

Real World Use Cases

SQL queries

string query = @"SELECT id, name
FROM users
WHERE is_active = 1";

Useful when writing readable database queries.

JSON samples or payloads

string json = """
{
  "id": 42,
  "status": "active"
}
""";

Helpful in tests, demos, and API requests.

Email or message templates

string email = @"Hello,

Your order has shipped.

Thanks,
Support Team";

File content generation

string config = @"server=localhost
port=8080
mode=development";

HTML or XML snippets

string xml = @"<user>
  <name>Alice</name>
</user>";

This is common in tests and small utility scripts.

Take Quiz

Real Codebase Usage

In real projects, developers often use multiline strings when they want code to stay readable and close to the final output.

Common patterns

1. Readable embedded SQL

string sql = @"
SELECT Id, Name
FROM Users
WHERE IsDeleted = 0";

This makes query structure easy to scan.

2. Test data setup

string expectedJson = """
{
  "success": true,
  "count": 2
}
""";

Tests become easier to understand when expected output looks like real output.

3. Early validation messages

string errorMessage = @"Validation failed:
- Name is required
- Email is invalid";

4. Configuration templates

string template = @"[database]
host=localhost
port=5432";

Important practice note

For SQL in real applications, multiline strings improve readability, but values should usually be passed as parameters, not hardcoded directly into the query string.

Example:

string sql = @"
SELECT Id, Name
FROM Users
WHERE Id = @Id";

This is safer and more maintainable than building SQL with string concatenation.

Common Mistakes

1. Forgetting that concatenation does not add line breaks

Broken example:

string text = "Hello" +
              "World";

Result:

HelloWorld

Fix:

string text = "Hello\n" +
              "World";

Or use a multiline string:

string text = @"Hello
World";

2. Using quotes incorrectly inside verbatim strings

Broken example:

string text = @"She said, "Hello"";

Fix: double the quote character inside a verbatim string.

string text = @"She said, ""Hello""";

3. Confusing verbatim strings with regular escaped strings

Regular string:

string path = "C:\\Temp\\file.txt";

Verbatim string:

string path = @"C:\Temp\file.txt";

When using @, you usually do not escape backslashes.

4. Accidentally including unwanted indentation

With multiline strings, spaces at the beginning of lines become part of the string.

string text = @"Line 1
    Line 2";

That indentation is stored too.

5. Choosing multiline strings when dynamic building is needed

If many values are inserted conditionally, simple multiline literals may not be enough by themselves. You may need interpolation, formatting, or a builder pattern.

Example:

int id = 42;
string query = $@"SELECT *
FROM Users
WHERE Id = {id}";

For SQL commands, prefer parameters instead of direct interpolation.

Comparisons

ApproachSyntaxBest forProsCons
Normal string"text"Short single-line textSimple and familiarEscaping and multiline formatting get messy
Concatenation"a" + "b"Combining small piecesWorks everywhereHard to read for long text
Verbatim string@"..."Multiline text, file pathsPreserves line breaks, easier backslashesQuotes inside need doubling
Raw string literal"""..."""Multiline text with quotes/JSONVery readable, minimal escapingRequires newer C# version
Interpolated string$"Hello {name}"Inserting valuesConvenient dynamic contentCan get messy with complex text
Interpolated verbatim$@"...{value}..."Multiline text with variablesMultiline plus interpolationStill requires care with formatting

Verbatim vs raw strings

FeatureVerbatim @"..."Raw """..."""
Multiline supportYesYes
Backslashes are literalYesYes
Easy to include quotesModerateUsually easier
Available in older C#YesNo
Great for JSON/templatesGoodExcellent
Take Quiz

Cheat Sheet

Quick syntax

Regular string

string s = "Hello";

Multiline with verbatim string

string s = @"Line 1
Line 2";

Multiline with raw string literal

string s = """
Line 1
Line 2
""";

Interpolated multiline string

string name = "Sam";
string s = $@"Hello,
{name}";

Rules to remember

  • Normal strings need escaping for backslashes: "C:\\Temp"
  • Verbatim strings treat backslashes literally: @"C:\Temp"
  • In verbatim strings, use "" to include a quote
  • Concatenation does not add spaces or line breaks automatically
  • Multiline strings preserve the text you write, including line breaks
  • Indentation inside the string may become part of the value

Good use cases

  • SQL queries
  • JSON/XML samples
  • Message templates
  • File paths
  • Test fixtures

Be careful

  • Do not build SQL by concatenating user input
  • Watch for unintended spaces and indentation
  • Use raw strings only if your C# version supports them

FAQ

Does C# support multiline strings?

Yes. You can use verbatim strings with @"..." and, in newer C# versions, raw string literals with """...""".

What is the easiest way to write a multiline string in older C#?

Use a verbatim string:

string text = @"Line 1
Line 2";

How do I include double quotes inside a C# verbatim string?

Use two double quotes:

string text = @"He said, ""Hi""";

Are multiline strings better than string concatenation?

Usually yes for readability, especially for SQL, JSON, templates, or text blocks.

What is the difference between verbatim and raw strings in C#?

Verbatim strings use @ and still require doubled quotes inside. Raw strings use triple quotes and are often easier for complex text.

Do multiline strings keep indentation?

Yes, any spaces included in the literal can become part of the string.

Should I use multiline strings for SQL queries?

Yes for readability, but use parameterized queries for safety rather than inserting values directly into the string.

Take Quiz

Mini Project

Description

Create a small C# console program that builds and prints a readable SQL query and a formatted email message using multiline string literals. This project shows how multiline strings make text-heavy code cleaner and easier to maintain.

Goal

Write and display multiline text in C# using verbatim strings and string interpolation.

Requirements

  1. Create a console application in C#.
  2. Define one multiline SQL query string.
  3. Define one multiline email message string.
  4. Print both strings to the console.
  5. Include one variable in the email output using string interpolation.
Take Quiz

Keep learning

Related questions

View more