Multiline string literal in C#

Multiline string literal in C#

You can use the @ symbol in front of a string to form a verbatim string literal:

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

You also do not have to escape special characters when you use this method, except for double quotes as shown in Jon Skeets answer.

Its called a verbatim string literal in C#, and its just a matter of putting @ before the literal. Not only does this allow multiple lines, but it also turns off escaping. So for example you can do:

string query = @SELECT foo, bar
FROM table
WHERE name = ab;

This includes the line breaks (using whatever line break your source has them as) into the string, however. For SQL, thats not only harmless but probably improves the readability anywhere you see the string – but in other places it may not be required, in which case youd either need to not use a multi-line verbatim string literal to start with, or remove them from the resulting string.

The only bit of escaping is that if you want a double quote, you have to add an extra double quote symbol:

string quote = @Jon said, This will work, - and it did!;

Multiline string literal in C#

As a side-note, with C# 6.0 you can now combine interpolated strings with the verbatim string literal:

string camlCondition = [email protected]
        <FieldRef Name=Resource/>
        <Value Type=Text>{(string)parameter}</Value>

Leave a Reply

Your email address will not be published.