9.3.6- Convert Your Variants into the Requisite Subtypes
by NT Community Manager.
|
| << 9.3.5- Use Include Files | Chapter9 | 9.3.7- Use a Variable Naming Convention (Consistently!) >> |
Convert Your Variants into the Requisite Subtypes
Earlier we talked about logical errors, one form of which is the type mismatch error. One way of avoiding type mismatches is to convert the value you're expecting from the user into the subtype needed for any calculations or manipulation before you perform any operations on the data. If you can't do this, then it's a fair guess that you're going to hit errors in your program. The VBScript conversion functions provide the ideal tools for performing conversions:
|
DataType to Convert to |
Function |
|
Boolean |
CBool |
|
Byte |
CByte |
|
Currency |
CCur |
|
Date |
CDate |
|
Double |
CDbl |
|
Integer |
CInt |
|
Long |
CLng |
|
Single |
CSng |
|
String |
CStr |
So, for example, to convert your user value to an integer you could do the following:
IntMyinteger = CInt(varUservalue)
The other functions are all used in the same way. Of course if you wish to convert a value, it's an idea to test the type of data you are converting; if the conversion is not possible then you will still end up generating an error. VBScript also presents some type check functions to help:
|
Function |
Purpose of Check |
|
IsArray |
Checks to see if the expression is an array |
|
IsDate |
Checks to see if the expression is a date |
|
IsEmpty |
Checks to see if the variable has been initialized |
|
IsNull |
Checks to see if the variable contains valid data or a NULL (unknown) value |
|
IsNumeric |
Checks to see if the expression is a number |
|
IsObject |
Checks to see if the expression is an object |
So, if you're expecting a variant containing data of a certain type, it might be a good idea to check for the type before converting. In our previous line of code, it would be wise to check and see whether the data contained is actually numeric, before trying to convert our data to integer format:
If IsNumeric(varUserValue) Then
IntMyinteger = CInt(varUservalue)
Else
Response.Write "A number is required"
End If
| << 9.3.5- Use Include Files | Chapter9 | 9.3.7- Use a Variable Naming Convention (Consistently!) >> |

RSS

