David,
* David said:
It's just a bug, it's not your misunderstanding of anything. My
favorite inconsistency here isn't the above, it's that
Dim i as Integer = CInt("&H" & Hex(someInteger))
can throw an exception. That tends to catch folks by surprise.
Visual Basic Language Reference -- Type Conversion Functions
<URL:
http://msdn.microsoft.com/library/en-us/vblr7/html/vagrptypeconversion.asp>
.... says:
"
If the 'expression' passed to the function is outside the range of the
data type to which it is being converted, an error occurs.
"
I assume 'CInt' and 'CLng' work as follows (simplified):
1. Treat the string as representation of an unsigned integer number, if
no sign is specified. To do that, first parse the number into the
largest integer datatype, this is 'System.Int64'. For values larger
than 'Int64.MaxValue' treat the number as signed number to make it
smaller.
2. Then try to convert the 'Int64' to the destination datatype. If the
number does not fit into this datatype, an exception is thrown.
Sample:
\\\
Dim s As String = "&H" & Hex(Integer.MaxValue) ' "&H80000000".
Dim i As Integer = CInt(s) ' Overflow exception.
///
"&H80000000" is converted to an integer number (/not/ the 'Int32'
datatype). The result is 2147483648, which is a positive integer
number. This number is larger than the maximum value that can be stored
in an 'Int32', 2147483647. An exception is thrown.
I think this behavior is "by design", and I would have chosen this
behavior too when implementing 'C*' methods. String literals containing
string representations of integer values should always be treated as
representations of the largest possible integer datatype, independent
from the 'C*' method called on the string expression.
Technically, I suppose that one could make the argument that since
there's virtually no documentation on the correct behavior of CInt/CLng
and all the C??? functions in general, that almost any behavior could be
deemed officially "correct". But one would hope for consistency at
least, I would think.
I think the behavior is consistent. Parsing an integer number cannot be
compared with parsing a string literal representing an integer number.
Int32.Parse("C5798A2F", Globalization.NumberStyles.HexNumber)
correctly returns -981890513
Mhm... For me, the VB.NET implementation is "correct".