3

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?

2
  • This has more to do with type promotion than type conversion. Commented Apr 18, 2011 at 20:49
  • There doesn't seem to be a 'type-promotion' tag. But yes, i think you are right. Commented Apr 18, 2011 at 20:56

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.