RN1 said:
Consider the following code snippet:
<%
Dim intA, strA, strB
intA=5
strA="Hello World"
strB=strA+intA
Response.Write(strB)
%>
The above code generates the "Type mismatch" error pointing to the
line strB=strA+intA but why doesn't VBScript implicitly cast the value
of intA into String when intA is concatenated with strA?
The + operator is overloaded to perform string concatenation when both
operands are strings (or one is a string the other is Empty).
It might have been preferable that it didn't even do that however when the
VB syntax was first intoduced in VB 1.0 the predecessor dialect of BASIC,
Microsoft Basic, used + to concatenate strings.
Apart from that + is a numerical plus operator and if either of the operands
is numerical in nature (even a boolean) both operands are coerced to a best
fit numerical type usually the type of the operand that has the widest
domain (e.g. Long + Double results in a Double).
Hence in the case of String + Integer or Integer + String the String will be
coerced to an Integer. Had strA been "10" the result would be 15.
As others have pointed out use & which is the string concatenation operator
and treat + as a purely numerical operator.
I am aware that VBScript supports only one data type which is Variant.
Thats a oversimplification.
VBScript supports a wide range of data types namely:- Null, Boolean, Byte,
Integer, Long, Float, Double, String, Decimal, Currency, Object (IDispatch),
Array of Variants.
A _variable_ in VB can have one of two types Variant or Array of Variants.
Its a mistake to think of VB only having one data type. It has many its
just that a single variable may hold a value of different types at various
points in the execution of code.