Implicit Type Coercion

Implicit type coercion is when a Variant variable changes its subtype automatically. Sometimes, this can work in your favor, and sometimes it can present a problem.

He is a code that asks the user for his age:

Dim lngAge
lngAge = InputBox("Plese enter your age in years")
If IsNumeric(ingAge) Then
lngAge = CLng(lngAge)
lngAge = lngAge + 50
MsgBox "In 50 years, you will be " & CStr(lngAge) & " years Old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If

Notice how we use the CLng ( ) and CStr ( ) functions to explicitly coerce the subtype. Well, in the case of this particular code, these functions are ot strictly necessary. The reason is that VBScript's inplicit type coercion would have done approximately the same thing for us. Here is the code again, without the conversion functions.

Dim lngAge
lngAge = InputBox("Plese enter your age in years")
If IsNumeric(ingAge) Then
lngAge = lngAge + 50
MsgBox "In 50 years, you will be " & lngAge & " years Old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If

Because of implicit type coercion, this code works the same way as the original code. Take a look at the fifth line. We did not explicitly coerce the subtype to Long, but the math still works as you would expect. Let us run the same code, but with some TypeName ( ) functions thrown in so that we can watch the subtypes change.

Next