I have the following code:
string hexString = "0x00000004";
Type hexType = typeof(Int32);
object o = Convert.ChangeType(hexString, hexType);
Which throws a System.FormatException as soon as it is executed as, apparantly, Convert.ChangeType can’t work with hexadecimal values.
My other alternatives are using either of these:
- Int32.Parse
- Convert.ToInt32
However, since they apply for a specific type, I’ll need to use a switch/reflection to choose the correct function for the correct type.
I am not really excited about either of these options. Is there anything else I can do?
Since hexadecimal is usually used only for integer numbers, you can parse the string to the largest integer type (Int64) and change the type of the result to the desired type:
(Note that you need to strip out the
0xprefix before passing the string to the Parse method.)Convert.ChangeType is essentially a big pile of
if (type == ...) ... else if (type == ...)statements. You could create a dictionary that maps all integer types to their respective Parse method: