Input: uint hex = 0xdeadbeef;
Required output: string result = "{deadbeef}"
First approach: Explicitly add the {
and }
; this works:
result = "{" + string.Format("{0:x}", hex) + "}"; // -> "{deadbeef}"
Output as decimal rather than hex using escaped curly brackets:
result = string.Format("{{{0}}}", hex); // -> "{3735928559}"
Seems promising, now all we need to do is add the :x
hex specifer as per the first approach above:
result = string.Format("{{{0:x}}}", hex); // -> "{x}"
Oh dear, adding the ':x
has made it output "{x}"
rather than the "{deadbeef}"
that I wanted.
So my question is: Must I solve this by explicitly adding the {
and }
as per the first example, or is there a way to do it using composite formatting and escaping the curly brackets?
Also note that this also affects string interpolation which (after all) is just converted by the compiler into a call to string.Format()
.
(This may well be duplicate question, but I have been unable to find a duplicate so far...)
edited
string.Format
. – Petersham"{{{0}}}"
shouldn't work either as0}
is not a valid parameter index, but since this works it is not consistent. – Petersham{{{0:N}}}
printing{N}
). – Kathyrnkati