String.Format and IFormattable.ToString(format, value) provides different result when trying to format to hexadecimal. How to get correct results when using IFormattable.ToString(format, value)
string format = "0x{0:X4}";
Console.WriteLine(string.Format(format, 255)); //prints- 0x00FF
IFormattable formattableValue = (IFormattable)255;
Console.WriteLine(formattableValue.ToString(format, null)); //prints- 25x{5:X4}
The format of the formatting string is different for string.Format()
and for ToString()
. In particular, string.Format()
allows for other text around the format, while IFormattable.ToString()
only allows the format specifier for the text itself.
In your example, the format string "0x{0:X4}"
is being treated as the whole format specifier for the value 255. The 0
are placeholders for digits, and the rest is just extra character literals.
If you want IFormattable.ToString()
to output the same as string.Format()
you have to use it in an equivalent way:
"0x" + formattableValue.ToString("X4", null);