This one came up today in an internal discussion alias and reminded me of how many times I’ve seen people get stumped on this one and end up working around it. A lot of users have used verbatim string literals as they ease writing multi-line strings literals or for specifying paths and not having to escape the backslashes (as Andrew pointed out in the comments for this post). Here’s an example:
string s = @”First line
string path = @”c:\windows\system”;
The trick with verbatim string literals is that everything between the delimiters (the double quotes that start and end the literal) is interpreted verbatim. So a the following line of code:
Console.WriteLine(@”First line\nSecond line.”);
will actually output:
First line\nSecond line.
So that’s easy to understand and comes in handy but some have trouble figuring out how to include an actual double-quote character in these literals. The answer is to use the quote-escape-sequence (two consecutive double-quote characters). Trying to escape the double-quote using a backslash (e.g. \”) will not work. The following line of code:
Console.WriteLine(@”Foo “”Bar”” Baz “”Quux”””);
will output the following:
Foo “Bar” Baz “Quux”
As always, you can find all the details in the C# language spec.