none
Bug in String.Format? RRS feed

  • Question

  • The following code:

    new IntPtr(20).ToString("x"

    produces the following result

    14 

    which is expected.

    But running this:

    String.Format("{0:x}"new IntPtr(20)) 

    which should produce the same result, intead produces this:

    20

    Bug?
    Monday, September 1, 2008 5:56 PM

Answers

  • The equivalent of IntPtr.ToString("x") is

          string s = String.Format("{0:x}", (int)(new IntPtr(20)));

    That's pretty questionable in 64-bit mode.  Add your vote to this feedback article.
    Hans Passant.
    • Marked as answer by Alex Ivanoff Monday, September 1, 2008 11:14 PM
    • Marked as answer by Alex Ivanoff Monday, September 1, 2008 11:14 PM
    Monday, September 1, 2008 6:10 PM
    Moderator

All replies

  • The equivalent of IntPtr.ToString("x") is

          string s = String.Format("{0:x}", (int)(new IntPtr(20)));

    That's pretty questionable in 64-bit mode.  Add your vote to this feedback article.
    Hans Passant.
    • Marked as answer by Alex Ivanoff Monday, September 1, 2008 11:14 PM
    • Marked as answer by Alex Ivanoff Monday, September 1, 2008 11:14 PM
    Monday, September 1, 2008 6:10 PM
    Moderator
  • Actually, this one is much better and 64-bit safe:

    String.Format("{0}"new IntPtr(20).ToString("x")) 

    Also, UIntPtr does not event have ToString overload that accepts formatting options. Why?

    I added my feedback, but considering the fact that there was no activity for 3 years I doubt it will ever get fixed.
    Monday, September 1, 2008 6:48 PM
  • The point was that IntPtr.ToString(string) isn't 64-bit safe.  It casts to int to invoke int.ToString(string).  Cast to (long) for a workaround.  Yeah, I wouldn't hold my breath waiting for a fix.
    Hans Passant.
    Monday, September 1, 2008 7:10 PM
    Moderator
  • I did not realize that IntPtr.ToString cast value to an integer: just checked it with Reflector. It is even worse than I thought. IntPtr.ToString is useless on x64 and Itenium! Nice.
    • Edited by Alex Ivanoff Monday, September 1, 2008 11:15 PM spelling
    Monday, September 1, 2008 11:14 PM