Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntPtr into hex string in string.Format

Note, I am not quite sure this question belongs to this site but I try to be constructive.

Why does the code

IntPtr ptr = new IntPtr(1234);
Console.WriteLine(string.Format("{0:X8}", ptr));
Console.WriteLine(ptr.ToString("X8"));
Console.WriteLine(string.Format("{0:X8}", ptr.ToInt32()));

output

1234
000004D2
000004D2

Why isn't the hex formatting applied to the IntPtr argument directly, when requested so in formatting? Are there any known arguments against designing the functionality so - ?
If there are no arguments against such design then by which channel should I report this issue to Microsoft?


Note also, that the debugger displays the IntPtr value in hex if requested so.
I find that it would be quite intuitive and relatively frequent way of printing out IntPtr values. I also have found code written by other people who used the first line and obviously expected the hex result, but actually the result was different. It also took some time for me to notice the issue, which complicated understanding the log messages.

like image 366
Roland Pihlakas Avatar asked Nov 11 '12 14:11

Roland Pihlakas


2 Answers

For the String.Format method to use a format string for an argument, the argument has to implement the IFormattable interface.

As the IntPtr type doesn't implement IFormattable, the String.Format method will just call the parameterless ToString method to turn the IntPtr value into a string.

like image 188
Guffa Avatar answered Oct 22 '22 10:10

Guffa


That is because in the first case, since IntPtr is not one of the built in integral types that work with String.Format, ptr.ToString() is invoked in order to return a string. Since the formatting is only applied after the conversion to a string, the X8 format specifier has no effect.

like image 2
driis Avatar answered Oct 22 '22 10:10

driis