views:

3704

answers:

3

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?

+20  A: 

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.

John Rasch
It's a string literal anyway - it's a *verbatim* string literal with the @ sign.
Jon Skeet
if your string contains double-quotes ("), you can escape them like so: "" ( thats two double-quote characters)
Muad'Dib
@Jon - thanks for the clarification, I'd delete this answer in lieu of yours but you probably already hit the max rep today :)
John Rasch
@Jon and @John, haha, both great answers, thanks. I'm not sure of proper SO protocol for choosing answers, but this one solved it for me first.
Chet
+16  A: 

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!";
Jon Skeet
You may want to also say that verbatim string literals use "" to escape double quotes.
Andrew Hare
I did, a few minutes ago :)
Jon Skeet
+6  A: 

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)
Martin Clarke
Thanks - I was googling for exactly this
Jaco Pretorius