Freigeben über


Double-quotes inside a verbatim string literal

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
                Second 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.

Comments

  • Anonymous
    August 11, 2005
    The comment has been removed
  • Anonymous
    August 11, 2005
    You're right Andrew. I use it for paths as well but also pretty infrequent. I was pretty focused on how people miss how to specify a double-quote when I wrote it but your comment should clear that up. Thanks...
  • Anonymous
    August 11, 2005
    ASP.NET Podcast #10 - Sahil Malik and Hilary Cotter [Via: http://www.scalabledevelopment.com/mcclure.htm...
  • Anonymous
    September 01, 2005
    The comment has been removed
  • Anonymous
    August 14, 2006
    Is this "verbatim string literal" valid in .NET 2.0. Is there an equivalent in 2.0

    The usage of the following syntax raises error. donno why?

    string strXML = @"<rules id="1">......"
  • Anonymous
    August 14, 2006
    Hi Dev,

    As noted in Gus' post, in order to use quotation marks within a verbatim string literal, you need to put double quotation marks.  The following should work:

    string strXML = @"<rules id=""1"">......";

    Is there something deeper to your question that I'm missing?  If so, or if you have any other questions, please feel free to contact me via my blog.
  • Anonymous
    September 11, 2006


    string a = "test";
    string s = """ + a + """;
    string r = @""" + a + @""";
    MessageBox.Show(s);
    MessageBox.Show(r);

    I want output as  "test", that is leading double quote inside the string. Isit possible ?

    I am not able to acheive the same.
  • Anonymous
    December 09, 2006
    I also struggled with the formatting. Your article helped me to move on. Thanks.