8

If you have a string with a numerous double quotes,

in PHP you can do this:

file.WriteLine('<controls:FormField Name="Strasse" LabelText="Strasse">');

in C# you have to do this:

file.WriteLine("<controls:FormField Name=\"Strasse\" LabelText=\"Strasse\">");

Is there a way in C# to do what you can do above in PHP, something like the @"c:\temp" which you can do so that you don't need double slashes?

Thanks Fredrik, that makes even quotes and curly brackets in a String.Format fairly readable:

    file.WriteLine(String.Format(@"<TextBox Text=""{{Binding {0}}}""
 Style=""{{DynamicResource FormularFieldTextBox}}""/>", fieldName));
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

4 Answers4

27

There are two ways to represent quotes in C# strings:

file.WriteLine("<controls:FormField Name=\"Strasse\" LabelText=\"Strasse\">");
file.WriteLine(@"<controls:FormField Name=""Strasse"" LabelText=""Strasse"">");
Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
7
"<controls:FormField Name='Strasse' LabelText='Strasse'>".Replace("'", "\"")

Which isn't great, but about the only option.

Or @"""" insted of \" you can use ""

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
  • 1
    Yeah, except what if you have `<...LabelText="O'Neil">`? Then suddenly you've replaced a legitimate single quote with double quotes, and now you've got some invalid XML... whoops. – Dan Tao Oct 20 '09 at 13:41
  • 1
    @Dan: Who names their child O'Neil, thats right up there with http://xkcd.com/327/ – Yuriy Faktorovich Oct 20 '09 at 13:52
  • @Yuriy, I can't tell if you're joking or being serious... (That xkcd comic is quite hilarious, though). – Dan Tao Oct 21 '09 at 16:49
  • On the fence for a +1 until I read the comic. Is that wrong? (Loudest in-public lol I've had in a while.) – ruffin Feb 02 '13 at 16:35
1

I would recommend avoiding some bizarre way like this:

const char doubleQuote = '"';

Console.WriteLine("<controls:FormField Name={0}Strasse{0} LabelText={0}Strasse{0}>", doubleQuote);
Greg
  • 16,540
  • 9
  • 51
  • 97
0

I would recommend using a resource file to store the string constants. This increases elegance and code readability. Also, quotes and special characters can be displayed without messing around with too many escape sequences.

You can create a resource file entry like,

String Name(Key) => FormFieldControl
Value => <controls:FormField Name="{0}" LabelText="{1}">

This can be used in code like

const string fieldName = "Strasse";
Console.WriteLine(ResourceFile.FormFieldControl, fieldName, fieldName);
Palladin
  • 983
  • 1
  • 7
  • 10