tags:

views:

137

answers:

4

For some reason the following C# Console program always outputs:

32
False
wtf=0

What am I doing wrong?

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Convert.ToUInt32("0x20", 16));
            UInt32 wtf = 0;
            Console.WriteLine(UInt32.TryParse("0x20",
                              NumberStyles.HexNumber, // I've tried also AllowHexSpecifier
                              CultureInfo.InvariantCulture,  // I've also tried CurrentCulture
                              out wtf));
            Console.WriteLine("wtf={0}", wtf);
        }
    }
}
+4  A: 

You need to drop the "0x" prefix. Please see this blog entry

Peter
You're absolutely right. So, does every C# programmer manually "trim-off" any "0x" (if present) or is there a short-cut?BTW: I'll accept this as solution as soon as SO allows me :-)
S.C. Madsen
Wow. That's close to a bug I would say.
kenny
@S.C. Madsen: I think I did "trim-off" "manually" when I needed this functionality in an earlier project. Not pretty, but worked well...
Peter
Peter: I've gone and done the same in my application. I really think this is a major short-coming of the TryParse() method.
S.C. Madsen
A: 

Get rid of the leading "0x" in the string you're trying to parse.

Brian
+1  A: 

See also http://msdn.microsoft.com/en-us/library/kadka85s%28v=VS.100%29.aspx In the example at the bottom of the page:

Attempted conversion of '0x8F8C' failed.

Simon
A: 

// stupid but effective way to improve the parsing

char[] _trim_hex = new char[] {'0','x'};

int temp;

if (int.TryParse(value.TrimStart(_trim_hex), NumberStyles.HexNumber, null, out temp)) { // temp is good }

Lance Kujala