Most readable way to assign a double quote to a string in C#
-
19-09-2019 - |
Question
Does anyone else think that escaping characters in very short strings make them not very readable? I noticed I was using s = "\""
in my code to assign a double quote a string, but having thought about it, I came up with the following alternative: s = '"'.ToString()
.
- Is my alternative any good? Would you prefer see the first version in code?
- How would you go about assigning two double quotes (""), which might be
s = "\"\""
, to a string?
/me is marking this CW before being pressured into it.
Solution
You could use:
String s = new String('"', 1);
or if you like to confuse people:
String s = @"""";
but actually I still prefer the good-old-fashioned escape: \"
OTHER TIPS
I'm not sure the alternative is more readable, on the contrary it's confusing. Besides, using a function call to have a different look in the source code doesn't make much sense - I would even say it's bad practice.
The old-fashioned escape sequence is the best option IMHO.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow