Putting \" in verbatim string with C# [duplicate]
Asked Answered
P

7

13

I need to print

a
"b"
c

with the vebatim string, I posed another question about multiple line code template here.

I tried with verbatim string as follows :

using System;

class DoFile {

    static void Main(string[] args) {
        string templateString = @"
        {0}
        \\"{1}\\"
        {2}
        ";
        Console.WriteLine(templateString, "a", "b", "c");
    }
}

But, I got this error.

t.cs(8,11): error CS1525: Unexpected symbol `{'
t.cs(9,0): error CS1010: Newline in constant
t.cs(10,0): error CS1010: Newline in constant

\"{1}\" doesn't work neither.

What's wrong?

Piping answered 13/5, 2011 at 18:46 Comment(0)
H
22

Try this ( "" instead of " to escape )

string templateString = @"
        {0}
        ""{1}""
        {2}
        ";

From C# specification: http://msdn.microsoft.com/en-us/library/Aa691090

quote-escape-sequence: ""

Highsmith answered 13/5, 2011 at 18:49 Comment(0)
E
8

In a verbatim string literal you use "" for double quote characters.

string line = @"
{0}
""{1}""
{2}";
Evangelicalism answered 13/5, 2011 at 18:48 Comment(0)
I
4

When using a multi-line string literal in C# with @", the correct escape sequence for a double-quote becomes "" instead of \".

    string templateString = @"
    {0}
    ""{1}""
    {2}
    ";
Imine answered 13/5, 2011 at 18:48 Comment(0)
S
1

In a verbatim string, use "" for a " in the result.

Shanelleshaner answered 13/5, 2011 at 18:48 Comment(0)
A
1

In an @" string, embedded double quotes are escaped as "",not \". Change your code to

    string templateString = @"
    {0}
    ""{1}""
    {2}
    ";

and your problems should go away.

Association answered 13/5, 2011 at 18:50 Comment(1)
Then lose the backslash. Edited to reflect the change.Association
H
0
string templateString = @"        
{0}        
""{1}""
{2}
";

EDIT: Updated to show correct syntax when using Verbatim.

Hachmann answered 13/5, 2011 at 18:49 Comment(2)
Incorrect. OP already notes this is wrong...Imine
@Imine - thanks - I will check my syntax firstHachmann
D
0

Use a "double double" quote to produce a single double quote in the output. It's the same way old VB6 would process strings.

@" ""something"" is here"; 

contains a string that has quotes around the something.

Deuce answered 24/8, 2011 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.