UInt32.TryParse() hex-number not working

S.C. Madsen picture S.C. Madsen · May 10, 2010 · Viewed 20.3k times · Source

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);
        }
    }
}

Answer

Peter picture Peter · May 10, 2010

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