DEV Community

IronSoftware
IronSoftware

Posted on

C# Multiline String (.NET Guide For Developers)

Multiline strings are everywhere in C# development — SQL queries, JSON templates, HTML fragments, error messages. For years, I wrote them with clunky escape sequences and string concatenation. Then C# introduced cleaner syntax that makes multiline text readable.

Here's how to write multiline strings properly.

using System;
// Install via NuGet: Install-Package System

string query = @"
SELECT Id, Name, Email
FROM Users
WHERE Status = 'Active'
ORDER BY Name
";
Enter fullscreen mode Exit fullscreen mode

The @ symbol creates a verbatim string literal. No escape sequences, actual line breaks in your code.

What's the Difference Between Regular and Verbatim Strings?

Regular strings require escape sequences for special characters:

string path = "C:\\Users\\Jacob\\Documents\\file.txt";
string message = "Line 1\nLine 2\nLine 3";
Enter fullscreen mode Exit fullscreen mode

Verbatim strings take the literal text:

string path = @"C:\Users\Jacob\Documents\file.txt";
string message = @"
Line 1
Line 2
Line 3
";
Enter fullscreen mode Exit fullscreen mode

I use verbatim strings for file paths, SQL queries, and any text with backslashes or line breaks. The code is cleaner and easier to read.

How Do I Include Quotes in a Verbatim String?

Double them:

string sql = @"
SELECT Name
FROM Users
WHERE Status = ""Active""
";
Enter fullscreen mode Exit fullscreen mode

Two double-quotes ("") become one double-quote in the string. It's the only escape you need in verbatim strings.

For JSON or nested quotes, this gets verbose:

string json = @"{
    ""name"": ""John"",
    ""age"": 30,
    ""city"": ""New York""
}";
Enter fullscreen mode Exit fullscreen mode

In C# 11, there's a better option: raw string literals.

What Are Raw String Literals?

C# 11 introduced raw string literals with triple quotes:

string json = """
{
    "name": "John",
    "age": 30,
    "city": "New York"
}
""";
Enter fullscreen mode Exit fullscreen mode

No escape sequences at all. The quotes stay as-is. The opening """ must be on its own line, and the closing """ determines the indentation to strip.

I switched all my JSON and HTML templates to raw strings. The code matches the output exactly.

How Do I Use Variables in Multiline Strings?

Combine $ (interpolation) with @ (verbatim):

string userName = "Alice";
int userId = 42;

string sql = $@"
SELECT *
FROM Orders
WHERE UserId = {userId}
  AND UserName = '{userName}'
";
Enter fullscreen mode Exit fullscreen mode

This is powerful for building dynamic SQL, HTML, or templates. But be careful with SQL injection — use parameterized queries in production:

// Better: use parameters, not string interpolation
var command = new SqlCommand(
    "SELECT * FROM Orders WHERE UserId = @userId",
    connection
);
command.Parameters.AddWithValue("@userId", userId);
Enter fullscreen mode Exit fullscreen mode

For display text or HTML generation, string interpolation in multiline strings is fine.

Can I Use Interpolation with Raw Strings?

Yes, prefix with $:

string name = "Jacob";
int year = 2025;

string message = $"""
Hello, {name}!

Welcome to C# in {year}.
This is a raw string literal with interpolation.
""";
Enter fullscreen mode Exit fullscreen mode

If you need curly braces in the output, use multiple $ symbols:

string css = $$"""
.container {
    color: {{color}};
    font-size: 16px;
}
""";
Enter fullscreen mode Exit fullscreen mode

With $$, you need double curly braces {{variable}} for interpolation. Single { and } become literal.

I use this for CSS or JavaScript templates where curly braces are common.

How Do I Convert a Multiline String to a Single Line?

Replace line breaks:

string multiline = @"
This is a
multiline string
with several lines.
";

string singleLine = multiline.Replace(Environment.NewLine, " ");
Console.WriteLine(singleLine);
// Output: This is a multiline string with several lines.
Enter fullscreen mode Exit fullscreen mode

Environment.NewLine handles platform differences (Windows uses \r\n, Unix uses \n).

For trimming and normalizing whitespace:

string normalized = string.Join(" ",
    multiline.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));
Enter fullscreen mode Exit fullscreen mode

I use this when parsing user input or cleaning up text from files.

How Do I Split Long Strings for Readability?

Concatenate across lines:

string message = "This is a very long error message that would " +
                 "extend beyond the editor width, so we split it " +
                 "across multiple lines for readability.";
Enter fullscreen mode Exit fullscreen mode

This doesn't create line breaks in the output — it's just for code formatting. The resulting string is one line.

Alternatively, use verbatim with explicit newlines:

string message = @"This is a very long message
that spans multiple lines and includes
actual line breaks in the output.";
Enter fullscreen mode Exit fullscreen mode

Choose based on whether you want the output on one line or multiple.

How Do Multiline Strings Apply to HTML and PDFs?

When generating HTML for PDFs with IronPDF, multiline strings make templates readable:

using IronPdf;
// Install via NuGet: Install-Package IronPdf

string customerName = "Alice";
decimal total = 1234.56m;

string html = $@"
<html>
<head>
    <style>
        body {{ font-family: Arial, sans-serif; }}
        .total {{ font-weight: bold; color: green; }}
    </style>
</head>
<body>
    <h1>Invoice</h1>
    <p>Customer: {customerName}</p>
    <p class='total'>Total: ${total:F2}</p>
</body>
</html>
";

var renderer = new [ChromePdfRenderer](https://ironpdf.com/blog/videos/how-to-render-html-string-to-pdf-in-csharp-ironpdf/)();
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Invoice.pdf");
Enter fullscreen mode Exit fullscreen mode

The multiline string keeps the HTML structure clear. I can copy-paste it into a browser to test styling before generating PDFs.

IronPDF's Chromium engine renders the HTML pixel-perfect, so what I see in Chrome is what appears in the PDF.

The full guide to multiline strings covers edge cases like mixing verbatim and interpolation with special characters.

What About SQL Queries?

Verbatim strings make SQL readable:

string query = @"
SELECT
    u.Id,
    u.Name,
    u.Email,
    COUNT(o.Id) AS OrderCount
FROM Users u
LEFT JOIN Orders o ON u.Id = o.UserId
WHERE u.Status = 'Active'
  AND u.CreatedDate >= @startDate
GROUP BY u.Id, u.Name, u.Email
ORDER BY OrderCount DESC
";
Enter fullscreen mode Exit fullscreen mode

I can format this exactly like I would in a SQL editor. When debugging, I copy it directly into SQL Server Management Studio.

Just remember: always use parameterized queries, never string interpolation, for user input.

Can I Embed Resources Instead?

For large templates, use embedded resources:

  1. Add a text file to your project (e.g., EmailTemplate.html)
  2. Set Build Action to "Embedded Resource"
  3. Load it at runtime:
using System.Reflection;
using System.IO;

var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyApp.EmailTemplate.html";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
    string template = reader.ReadToEnd();
}
Enter fullscreen mode Exit fullscreen mode

I use embedded resources for large HTML emails or complex PDF templates. Multiline strings are better for short, inline templates.

Quick Reference

Syntax Use Case Example
@"..." Verbatim string (escape \, line breaks) File paths, SQL
$@"...{var}..." Verbatim + interpolation Dynamic SQL, templates
"""...""" Raw string (C# 11+, no escapes) JSON, HTML with quotes
$"""...{var}...""" Raw + interpolation CSS, JavaScript templates
"line1" + "line2" Concatenation (no output breaks) Readability splitting

Key Principles:

  • Use @ for paths and SQL to avoid escape hell
  • Use """ for JSON and HTML when you can target C# 11+
  • Combine $ and @ for dynamic templates
  • Always parameterize SQL queries, never interpolate user input

Multiline strings make your code match the domain. SQL looks like SQL, HTML looks like HTML, JSON looks like JSON. That's the point.


Written by Jacob Mellor, CTO at Iron Software. Jacob created IronPDF and leads a team of 50+ engineers building .NET document processing libraries.

Top comments (0)