IFormattable.ToString does not work as expected for hexadecimal formatting

String.Format and IFormattable.ToString (format, value) provide different results when trying to format in hexadecimal format. How to get the 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}
+4
source share
1 answer

The format string format is different for string.Format()and for ToString(). In particular, string.Format()it allows the use of other text around the format, and IFormattable.ToString()only the format specifier allows for the text itself.

"0x{0:X4}" 255. 0 , - .

, IFormattable.ToString() , string.Format(), :

"0x" + formattableValue.ToString("X4", null);
+2

Source: https://habr.com/ru/post/1616310/


All Articles