Kratz
Kratz

Reputation: 4330

VB Compiler Conversion from string to number

This is more of a curiosity question on what the VB compiler is doing. Basically the following code generates an error,

    If "String" = CInt(1) Then

    End If

As it should. What makes me curious is the error reported is

Conversion from string "String" to type 'Double' is not valid.

So, I guess my question is, why is the compiler attempting to convert to a Double when i would assume it should be converting to Integer?

Upvotes: 3

Views: 5031

Answers (1)

Sachin Chavan
Sachin Chavan

Reputation: 5614

Following can give some hint.

For following

If "String" = CInt(1) Then

End If

The innerexception stacktrace shows

at Microsoft.VisualBasic.CompilerServices.Conversions.ToDouble(String Value, NumberFormatInfo NumberFormat)
at Microsoft.VisualBasic.CompilerServices.Conversions.ToDouble(String Value)

Even if you change the statement as

If "String" = CDbl(1) Then

or

If "String" = CDec(1) Then

It still shows the innerexception stacktrace as given above.

It means it has to do nothing with the right hand side value. It is behavior of compiler while doing implicit conversion to convert the string to more accommodating data type which is double(long would be too long-pun intended ).

This behavior can be proved by changing the statement to :

If CInt("String") = CLng(1) Then

End If

For this the innerexception stacktrace shows

at Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat)
at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value)

Which means even for explicit type conversion it first tries to convert the string to double(most accommodating) and then converts it to integer.

Upvotes: 2

Related Questions