C# 101 - Representing a double quote in string literals

I'm sure almost every C# developer already knew this, but I thought a post might help the few that didn't. I had always wondered how it was done and stumbled across it yesterday buried in an example in the C# Language Specification.

If you want to represent a double quote in a string literal, the escape sequence is two double quotes.

string myString = @"<xml attribute=""my attribute""/>";

I have found this useful for storing nicely formatted XML fragments in constants without resorting to 1) putting it all on one long line without string literals or 2) loading from a file or resource or 3) concatenating at run time, or 4) switching to single quotes.

  private const string requestXml =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope
 xmlns:xsi=""
http://www.w3.org/2001/XMLSchema-instance""
 xmlns:xsd=""
http://www.w3.org/2001/XMLSchema""
 xmlns:soap=""
http://schemas.xmlsoap.org/soap/envelope/"">
 <soap:Body>
  <ForceBuild xmlns=""
http://tempuri.org/"">
   <projectName><![CDATA[{0}]]></projectName>
  </ForceBuild>
 </soap:Body>
</soap:Envelope>";

Now I know.

19 Comments

Comments have been disabled for this content.