Ben
Ben

Reputation: 5777

C# Declare a string that spans on multiple lines

I'm trying to create a string that is something like this

string myStr = "CREATE TABLE myTable
(
id text,
name text
)";

But I get an error: https://i.sstatic.net/o6MJK.png

What is going on here?

Upvotes: 14

Views: 31618

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112299

Make a verbatim string by prepending an at sign (@). Normal string literals can't span multiple lines.

string myStr = @"CREATE TABLE myTable
(
    id text,
    name text
)";

Note that within a verbatim string (introduced with a @) the backslash (\) is no more interpreted as an escape character. This is practical for Regular expressions and file paths

string verbatimString = @"C:\Data\MyFile.txt";
string standardString = "C:\\Data\\MyFile.txt";

The double quote must be doubled to be escaped now

string verbatimString  = @"This is a double quote ("")";
string standardString  = "This is a double quote (\")";

Starting with C# 11, we can use raw string literals. They allow you to preserve the indentation of your code while the indentation white spaces are not added to content of the string itself. In the following example CREATE is left aligned on the first line of the string. The position of the ending """ marks the left edge of the string. The end of the string is ) with no line-break following it. The double quotes need not to be escaped.

    string myStr = """
        CREATE TABLE "myTable"
        (
            "id" text,
            "name" text
        )
        """;

Upvotes: 28

Petur Subev
Petur Subev

Reputation: 20193

Use the @ symbol infront of the string.

Upvotes: 3

Ozerich
Ozerich

Reputation: 2000

string myStr = @"CREATE TABLE myTable
(
id text,
name text
)";

Upvotes: 8

Related Questions