Home >Backend Development >C++ >How Can I Efficiently Create Multiline Strings in C#?

How Can I Efficiently Create Multiline Strings in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-23 06:26:08899browse

How Can I Efficiently Create Multiline Strings in C#?

Creation of multi-line string literals in C#

In C#, you can create multi-line string literals using the @ (literal string) prefix. This allows you to define multiline strings without concatenating or using special syntax.

Question:

Consider the following code snippet:

<code class="language-c#">string query = "SELECT foo, bar"
+ " FROM table"
+ " WHERE id = 42";</code>

This code creates a multiline string by concatenating multiple string literals. How can I achieve the same result using a more efficient and concise syntax?

Answer:

To create a multiline string using verbatim string literals in C#, use the @ symbol in front of the string:

<code class="language-c#">string query = @"SELECT foo, bar
FROM table
WHERE id = 42";</code>
The

@ symbol indicates that subsequent strings should be treated as verbatim strings. This means that all characters in the string will be interpreted literally, including spaces and special characters (except double quotes).

By using verbatim string literal syntax, you can avoid the tedious concatenation process and keep your code readable. Double quotes are still required to enclose the string content, and escape sequences (e.g. n for newline) are ignored unless you want to represent double quotes (").

The above is the detailed content of How Can I Efficiently Create Multiline Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn