TomCaps
TomCaps

Reputation: 2527

How to write a string that starts with @ and contains " " in C#

When I change the following C# string

string xml="xmlns:qtpRep=\"http://www.mercury.com/qtp/ObjectRepository\""

into

string xml=@"xmlns:qtpRep=\"http://www.mercury.com/qtp/ObjectRepository\""

I get compiler error: ;expected
How can I express the literal double quotes inside a string starting with @ ?

Upvotes: 1

Views: 241

Answers (3)

Alex
Alex

Reputation: 23300

Two double quotes translate to a single quote when the string is verbatim (with @).

For example:

Console.WriteLine(@"this is ""enclosed in double quotes""");

...will write:

this is "enclosed in double quotes"

Upvotes: 2

user47589
user47589

Reputation:

Double them up:

 string xml = @"xmlns:qtpRep=\""http://www.mercury.com/qtp/ObjectRepository\""";

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500485

You double the double quotes instead of using a backslash:

string xml = @"xmlns:qtpRep=""http://www.mercury.com/qtp/ObjectRepository""";

(See MSDN for more details.)

Although in this case it's not clear why you want a verbatim string literal anyway... and for XML attributes it's generally simpler just to use single quotes:

string xml = @"xmlns:qtpRep='http://www.mercury.com/qtp/ObjectRepository'";

I'm also bound to say that if you're creating XML strings yourself, you're probably Doing It WrongTM. Use an XML API instead :)

Upvotes: 10

Related Questions