Question

To escape or to verbatim, that is my question.

I need to programmatically send a couple of commands to a (Zebra QLn220) printer in C#, specifically:

! U1 setvar "power.dtr_power_off" "off"

-and:

! U1 setvar "media.sense_mode" "gap"

Due to the plethora of quotes in these commands, I thought it would be sensible to use verbatim strings. But based on this, I still need to double the quotes, so that it would presumably/theoretically need to be like:

string dontShutErOff = @"! U1 setvar """power.dtr_power_off""" """off"""";

...which looks like a mashup composed of Don King, the cat from Coding Horror, and Groucho Marx.

Would it be better to escape the quotes this way:

string dontShutErOff = "! U1 setvar \"power.dtr_power_off\" \"off\"";

?

Should I Escape from Verbatimtraz?

UPDATE

Based on Eric Lippert's first suggestion, how about this:

const string quote = "\"";
string whatever = string.Format("! U1 setvar {0}power.dtr_power_off{0} {0}off{0}", quote);
Était-ce utile?

La solution

I would consider a third alternative:

const string quote = "\"";
string whatever = "! U1 setvar " + 
                  quote + "power.dtr_power_off" + quote + " " +
                  quote + "off" + quote;

Or a fourth:

static string Quote(string x) 
{
    const string quote = "\""; 
    return quote + x + quote;
}
...
string whatever = "! U1 setvar " + Quote("power.dtr_power_off") + " " + Quote("off");

All these have pros and cons; none is clearly the best.

Autres conseils

Resources may be better approach - it looks like you planning to have C# constants to have names anyway.Let resource auto-generation to create C# constant for you while editing commands as regular text.

Verbatim strings don't allow double quotes as you've described in your first example. It won't compile.

I juts found this out actually... It does support double-double quotes as quotes. So your first example would look like this:

string dontShutErOff = @"! U1 setvar ""power.dtr_power_off"" ""off""";

However, if your string literals are important, won't likely change, or may need to be translated in the future, I would put them in a resource file as mentioned in a previous answer. Any escaping is done automatically and the string is easily readable.

Your first line should be:

string dontShutErOff = @"! U1 setvar ""power.dtr_power_off"" ""off""";

Quotation marks are written as double quotation marks, not triple.

Neither way is clearly better than the other, at least not for quotation marks. It's mostly a matter of taste. In other situations one way or the other has clear advantages, for example using a @ delimited string for file paths that contain backslashes.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top