Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Verbatim or escaping the preferred way to deal with quote-rich strings in C#?

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);
like image 305
B. Clay Shannon-B. Crow Raven Avatar asked Dec 01 '25 00:12

B. Clay Shannon-B. Crow Raven


1 Answers

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.

like image 59
Eric Lippert Avatar answered Dec 03 '25 13:12

Eric Lippert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!