-2

I have this substring I want to strip out of a string:

<ArrayOfSiteQuery xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://schemas.datacontract.org/2004/07/CStore.DomainModels.HHS">

Realizing it was full of funkiness, I thought verbatimizing it would solve all ills:

String messedUpJunk = @"<ArrayOfSiteQuery xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://schemas.datacontract.org/2004/07/CStore.DomainModels.HHS">";

...but, to paraphrase the robot on Lost In Space, that does not compute (compile); I get, "; expected" on the first "http".

I can get it compilable by escaping the quotes:

String messedUpJunk = "<ArrayOfSiteQuery xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/CStore.DomainModels.HHS\">";

...but what use is verbatim if it's not verbatimatic?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    think about it, how could compiler possibly know where your string literals starts and ends if you don't escape `"`? – Selman Genç Jan 07 '15 at 19:51
  • I would think verbatimizing should just tell the compiler "forget about trying to figure this out - just consider everything within the inner and outer quotes as a single string that you shouldn't mess with or try to parse." – B. Clay Shannon-B. Crow Raven Jan 07 '15 at 19:58

2 Answers2

6

A double quote is the only character you need to escape in verbatim strings. Escaping it is done differently, you need to double it ("") instead of using the backslash:

String messedUpJunk = @"<ArrayOfSiteQuery xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" 
xmlns=""http://schemas.datacontract.org/2004/07/CStore.DomainModels.HHS"">";

MSDN link:

Use double quotation marks to embed a quotation mark inside a verbatim string

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
3

It is the double quote which requires escaping (using double double quotes), for rest of the characters you don't need to escape, for example back slash \.

See: 2.4.4.5 String literals - C#

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.

The reason you need to escape double quote is because it represents start and end of string, whether verbatim or regular.

Habib
  • 219,104
  • 29
  • 407
  • 436