Keywords: C# | multiline strings | string literals | verbatim strings | raw strings
Abstract: This article provides an in-depth exploration of multiline string literals in C#, focusing on verbatim string literals (@"") and raw string literals (""""""). Through detailed code examples and comparative analysis, it explains how to efficiently handle multiline text in C# development, including common application scenarios such as SQL queries and XML/JSON data embedding. The article also covers string interpolation, special character handling, and the latest improvements in recent C# versions, offering comprehensive technical reference for developers.
Introduction
In C# programming practice, handling multiline text data is a common requirement. Traditional string concatenation methods are not only verbose but also prone to errors. Based on high-scoring Stack Overflow answers and official documentation, this article systematically introduces the implementation mechanisms of multiline string literals in C#.
Verbatim String Literals Fundamentals
Verbatim string literals are the most classic way to create multiline strings in C#. By prefixing the string with the @ symbol, all characters in the string are preserved, including newlines and most special characters.
string sqlQuery = @"SELECT foo, bar
FROM table
WHERE id = 42";
Compared to traditional string concatenation:
// Traditional concatenation
string query = "SELECT foo, bar"
+ " FROM table"
+ " WHERE id = 42";
// Verbatim string approach
string query = @"SELECT foo, bar
FROM table
WHERE id = 42";
The advantages of verbatim strings include:
- More concise and intuitive code
- Preservation of original formatting for better readability
- Reduced use of escape characters
Special Character Handling
In verbatim strings, most special characters don't require escaping, but double quotes are an exception. You need to escape double quotes by adding another double quote:
string message = @"Jon said, ""This will work,"" - and it did!";
This approach makes embedding quotes in strings straightforward, particularly useful for text content containing numerous quotes, such as SQL statements or JSON data.
Raw String Literals (C# 11+)
C# 11 introduced raw string literals, providing more powerful multiline string handling capabilities. Raw strings use three or more double quotes as delimiters:
string xmlContent = """
<element attr="content">
</element>
""";
Core features of raw string literals include:
Flexible Delimiters
When the string content contains three consecutive double quotes, you can use four double quotes as delimiters:
string complexString = """"
This string contains """ triple quotes
"""";
Automatic Indentation Handling
Raw string literals automatically handle code indentation, ensuring separation between string content and code formatting:
var formattedText = """
This text will be dedented
to remove the leading spaces
""";
String Interpolation with Multiline Strings
Combining string interpolation functionality allows creating multiline strings with dynamic content:
int userId = 42;
string dynamicQuery = $"""
SELECT foo, bar
FROM table
WHERE id = {userId}
""";
For more complex interpolation scenarios, multiple $ symbols can be used to handle braces:
var jsonTemplate = $$"""
{
"user": {
"id": {{userId}},
"name": "{{userName}}"
}
}
""";
Practical Application Scenarios
SQL Query Construction
Multiline strings are particularly useful in database operations:
string complexQuery = @"
SELECT
u.name,
u.email,
COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.active = 1
GROUP BY u.id, u.name, u.email
ORDER BY order_count DESC";
HTML/XML Templates
In web development, multiline strings are commonly used for template definitions:
string emailTemplate = """
<!DOCTYPE html>
<title>Welcome Email</title>
Welcome, {0}!
Thank you for registering.
""";
Regular Expression Patterns
Complex regular expression patterns are clearer when using multiline strings:
string emailPattern = @"
^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+
@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?
(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$";
Performance Considerations and Best Practices
String Immutability
Strings in C# are immutable, and frequent string concatenation creates numerous temporary objects. Using multiline string literals can reduce this overhead:
// Not recommended: creates multiple temporary strings
string badExample = "Line 1" + "\n" + "Line 2" + "\n" + "Line 3";
// Recommended: single allocation
string goodExample = @"Line 1
Line 2
Line 3";
Memory Usage Optimization
For very large multiline strings, consider using StringBuilder or stream processing:
// Suitable for medium-sized multiline text
var mediumText = @"...";
// Suitable for very large text
var largeTextBuilder = new StringBuilder();
largeTextBuilder.AppendLine("Line 1");
largeTextBuilder.AppendLine("Line 2");
// ... more lines
Version Compatibility Considerations
When choosing multiline string implementation methods, consider the C# version used in your project:
- C# 1.0+: Supports verbatim string literals (@"")
- C# 6.0+: Supports string interpolation combined with verbatim strings ($@"")
- C# 11.0+: Supports raw string literals ("""""")
Debugging and Maintenance Techniques
Visual Debugging
In Visual Studio, multiline strings maintain their original format during debugging, making them easier to inspect:
// Displays as formatted multiline text in debugger
string debugText = @"
First line
Second line
Third line";
Code Maintenance
When using multiline strings, it's recommended to:
- Maintain consistent indentation style
- Add blank lines before and after long strings for better readability
- Add comments explaining complex multiline strings
Conclusion
C# provides multiple powerful mechanisms for handling multiline strings, from classic verbatim strings to modern raw string literals. Developers can choose appropriate solutions based on project requirements and C# versions. Verbatim strings are suitable for most scenarios, while raw string literals offer better flexibility and readability when dealing with complex text formats. Proper use of these features can significantly improve code quality and development efficiency.