Is there an easy way to create a multiline string literal in C#?
Here's what I have now:
string query = "SELECT foo, bar"
+ " FROM table"
+ " WHERE id = 42";
I know PHP has
<<<BLOCK
BLOCK;
Does C# have something similar?
Is there an easy way to create a multiline string literal in C#?
Here's what I have now:
string query = "SELECT foo, bar"
+ " FROM table"
+ " WHERE id = 42";
I know PHP has
<<<BLOCK
BLOCK;
Does C# have something similar?
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 Skeet's answer.
It's called a verbatim string literal in C#, and it's 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 = 'a\b'";
The only bit of escaping is that if you want a double quote, you have to double it:
string quote = @"Jon said, ""This will work,"" - and it did!";
One other gotcha to watch for is the use of string literals in string.Format. In that case you need to escape curly braces/brackets '{' and '}'.
// this would give a format exception
string.Format(@"<script> function test(x)
{ return x * {0} } </script>", aMagicValue)
// this contrived example would work
string.Format(@"<script> function test(x)
{{ return x * {0} }} </script>", aMagicValue)