To escape double quotes in a verbatim string (ie, a string declared with the @
prefix), simply double the quotes up (""
). This is in contrast to how you would normally escape a double quote in a string, \"
.
var stringHolder = @" book book ""book""
ten ten ""book"" book pen
pen ""hook book"" dook
beer poor ""111"" cat map";
Console.WriteLine(stringHolder);
/*Output:
book book "book"
ten ten "book" book pen
pen "hook book" dook
beer poor "111" cat map
*/
When the indentation matters, you may have to fight the normal tabbing in your editor a bit, which can lead to some odd looking declarations.
namespace MyNamespace {
public class Foo {
public string GetString() => @"Hello
World"; // Returns a string that looks like
// Hello
// World
public string GetString2() => @"Hello
World"; // Returns a string that looks like
// Hello
// World
}
}
While this feature is currently in preview for C# 11, the following way of declaring multi-line strings that contain quotes is likely to be available in the coming future.
var stringHolder = """
book book "book"
ten ten "book" book pen
pen "hook book" dook
beer poor "111" cat map
""";
Console.WriteLine(stringHolder);
/*Output:
book book "book"
ten ten "book" book pen
pen "hook book" dook
beer poor "111" cat map
*/
At the moment, the rules for how many quotes (in this example, 3) that are required is that the header and footer quotes be at least 3, or N+1 the amount of consecutive quotes expected in the string.