|Datatypes in VbScript|
Data Types in VBScript:
VBScript has only one data type called a Variant. A Variant is a kind of super data type that can contain different kinds of information.So in nutshell the variant is a special data type that can store many different subtypes. Some other thought says that variant is merely a container for several other data types.
A variant data type changes automatically depending on what kind of data the variable is holding. This concept becomes important when we have VBScript code that needs to interact with COM components.(They may be written in VB,C++ or other COM enabled languages).
The downside of variant is that it takes up more spaces (memory) than many of the specified VB data types.
This post will help you to understand the following topics as well:
- what is variant data type in vbscript?
- is there any Datatype in Vbscript?
- data type in vbscript
VBScript is a loosely typed Language:
In Vbscript the coder need not have to declare the data type of a variable.However what kind of data the variable holds still matters to WSH. A loosely typed language does not provide a way to declare type of a variable. This is the reason we don’t see datatypes in VBScript.
In VbScript we have a super type fit for all, universal data type called Variant.Variant is the only data type in VBScript, It is same data type returned by all functions in VBScript. It is kind of one fits for all.A subtype is a type within the type.
A variant is a type or called super type and remaining all other subtypes are the child type.
In other words a variant is a generic container in which all subtypes resides.
A variant can hold only one of the subtype at a time.The process of changing subtypes are called type conversion or implicit type coercion.By default the variant subtype will be integer.
The below discussion is very useful while designing automation framework.
Subtype of Variant:
There are two major subtypes of Variant data type:
When we change a subtype and a new value gets assigned to a variant variable, in that case an implicit change in the data subtype happens.In this case the VBScript engine checks the new data and determine automatically what subtype is should be. This automatic conversion is called Implicit type conversion.
Why Implicit option is not good always?
When we ask VBScript engine to define and store a data, it may select any of the relevant subtypes to store the data.Like a numeric data 5 can b stored in String,integer,long or byte.
On the other hand,if we want to make sure that the numeric data is stored inside predefined datatype like integer,we need to use CInt() conversion function.This will ensure that the number 5 is stored as Integer not any other data type.
Implicit type Conversion:
This is a technique where variant variable changes its subtype as per engine defined rules automatically.
Dim a a=InputBox("Enter a Number that will be multiplied by 10") Msgbox TypeName(a) If IsNumeric(a) Then Msgbox TypeName(a) a=a*10 Msgbox TypeName(a) Msgbox "Multiplied by 10 gives"&a Else Msgbox "Wrong Input" End If
Here a is changed from String to int to long based on the content.We can test the type value by using TypeName() method.The first TypeName is String as WSH notices that the data is coming from InputDialogBox. The second TypeName is calculated based on the number we provide. The third TypeName is calculated when the resultant number is too long for integer.
The second way to change a subtype to a variant is explicit type conversion.In this process instead of automatic type identification ,the coders themselves takes specific measures to change the subtype. This type of conversions are done with different VBScript syntaxes and conversion functions.
We can also declare a variable implicitly by simply using its name in our script. That is not generally a good practice because we could misspell the variable name in one or more places, causing unexpected results when our script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables.
Option Explicit in VBScript:
The Option Explicit statement should be the first statement in our script.Forces explicit declaration of all variables in a script.As in VBScript,the variable declaration is optional ,that signifies that we can declare or we may not declare a variable before using it.Even though this feature makes the VBScript engine very fast but can cause issues if we do spelling mistake.(VBScript may not catch the spelling mistake a error instead it will create a new variable which may create a bug). To overcome this issue VBScript provides a powerful concept called Option Explicit. We need to put it in the first line of the script. It tells the VBScript engine that all variables used in the script are explicitly declared before they are used. It stop spelling mistake of a variable as a new variable.
Option Explicit ' Force explicit variable declaration. Dim MyVar ' Declare variable. MyInt = 10 ' Undeclared variable generates error. MyVar = 10 ' Declared variable does not generate error.
VBScript Variant Subtypes:
Beyond the simple numeric or string classifications, a Variant can make further distinctions about the specific nature of numeric information. For example, we can have numeric information that represents a date or a time. When used with other date or time data, the result is always expressed as a date or a time. We can also have a rich variety of numeric information ranging in size from Boolean values to huge floating-point numbers. These different categories of information that can be contained in a Variant are called subtypes. Most of the time, we can just put the kind of data we want in a Variant, and the Variant behaves in a way that is most appropriate for the data it contains.
The following table shows subtypes of data that a Variant can contain.
VBScript Subtype Description:
This list is very much useful while working with data types.
|Subtype||Description||Test Function||varType()||TypeName() return value|
|Empty||A variant is uninitialized. Value is 0 for numeric variables or a zero-length string (“”) for string variables.No Conversion function available.||IsEmpty()-returns True/False based on the variable under test is initialized or not.||0(vbEmpty)||Empty|
|Null||Variant intentionally contains no valid data..No Conversion function available||IsNull()-returns True/False based on the variable under test is having any data or not||1(vbNull)||Null|
|Boolean||Contains either True or False. Conversion function -CBool()||No Test function||11(vbBoolean)||Boolean|
|Byte||Contains integer in the range 0 to 255.|
|IsNumeric()-returns True/False based on the variable under test is numeric or not.||17(vbByte)||Byte|
|Integer||Contains integer in the range -32,768 to 32,767.Conversion function-CInt()||IsNumeric()-returns True/False based on the variable under test is numeric or not.||3(vbInteger)||Integer|
|Currency||-922,337,203,685,477.5808 to 922,337,203,685,477.5807.Conversion function-CCur()||IsNumeric()-returns True/False based on the variable under test is numeric or not.||6(vbCurrency)||Currency|
|Long||Contains integer in the range -2,147,483,648 to 2,147,483,647.Conversion function-CLng()||IsNumeric()-returns True/False based on the variable under test is numeric or not.||2(vbLong)||Long|
|Single||Contains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.Conversion function-CSng()||IsNumeric()-returns True/False based on the variable under test is numeric or not.||4(vbSingle)||Single|
|Double||Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.Conversion function-CDbl()||IsNumeric()-returns True/False based on the variable under test is numeric or not.||5(vbDouble)||Double|
|Date (Time)||Contains a number that represents a date between January 1, 100 to December 31, 9999.Conversion function-CDate()||IsDate()-returns True/False based on the variable under test is Date or not.||7(vbDate)||Date|
|String||Contains a variable-length string that can be up to approximately 2 billion characters in length.Conversion function-CStr()||None||8(vbString)||String|
|Object||Contains an object.|
No Conversion function available
|Error||Contains an error number.|
No Conversion function available
|No Test Function||10(vbError)||Error|
|Variant||Super type for all|
|No Test Function||12(vbVariant)||Variant|
|Decimal||Contains decimal data.|
No Conversion function available
|IsNumeric()-returns True/False based on the variable under test is numeric or not.||14(vbDecimal)||Decimal|
|Array||Contains multiple data|
No Conversion function available
|IsArray()-returns True/False based on the variable under test is array or not.||8192(vbArray)||Array|
We can use conversion functions to convert data from one subtype to another. In addition, the VarType function returns information about how your data is stored within a Variant.
There are two more functions that also can be considered as Test functions:
- IsFinite()-returns True/False based on the variable under test is finite or not.
- IsNaN()-returns True/False based on the variable under test is NAN (Not a Number)or not.
How to check data type of a variant variable?
There are two inbuilt functions in VBScript that returns the datatype of a variant in two different flavors.
The functions to check datatype as follows:
This function returns a numeric representation of the underlying subtype of the variant.
This function returns a String representation of the underlying subtype of the variant.
Dim a a="xyz" msgbox VarType(a) //also it can be coded like below: If VarType(a)=VBString Then msgbox "Hello" End If //also can be expressed as: If VarType(a)=8 Then msgbox "Hello" End If
For Constants in VBScript Please refer here. However if we write values instead of the named constants,it will create issues in understanding later. The named constants improved readability and understandability of the expression.
Force Datatype change in Vbscript:
This is a very useful concept while designing the UFT script or VBScript or QTP script.
dim a a=10 msgbox TypeName(a)//output as integer a="10" msgbox TypeName(a)//output as String a=CLng(a) msgbox TypeName(a)//output as long //this is often referred as side effect of CLng() function.
Empty is a subtype of variant.When we define a variable but not assign a value to int,it is Empty and its type is also empty.Empty is implicit as the WSH engine assigns it by default.
Dim a Msgbox TypeName(a)
we can not work with this Empty data type or Empty variable.We can however convert an Empty to other sub data type.If the conversion type is of the numeric type then the value is converted to zero(0) by default.If the conversion is of String type, it will create a empty zero sized or length based String.
How to check if a datatype is empty?
There is a function called IsEmpty() that returns a boolean value,depending on emptiness of the variable.
A variant can hold Null value once the coder has explicitly assigned a Null to a variable. Null datatype says there is no value or the value is unknown. Null is explicit as either coder has to to do it or some external trigger like Database,Some query or some functions can produce it.
Empty Vs Null- comparison
- Empty data type indicates that the variable is declared but not assigned with any value whereas Null indicates that the variable does not hold any valid data. Or the Null also signifies that the variable is assigned with a NULL subtype.
- Empty is implicit and Null is explicit.
How to assign Null value to a variable in VBScript?
Dim a; //now a is empty not Null a=Null //Null is assigned to a
We can not compare a variable having Null value using = operator,We need to use IsNull() function to test if a variable is Null.
//illegal If a=Null Then Msgbox "a is Null" End if //legal If IsNull(a) Then Msgbox "a is Null" End if
Invalid Use of Null Issue in VBScript or UFT or QTP
We need to be careful about working with a variable having Null value.In an expression,if one variable holds Null,the expression can not be evaluated.Instead VBScript engine will throw an error message as “Invalid use of Null”
Dim a,b,c a=Null b=5 c=a+b Msgbox c Msgbox TypeName(c) //output Null
This is a very popular error code when UFT/QTP tries to read from Database and tries to do some operation.The better way to work with it is to check using IsNull() and then assign some value based on TypeName() function.
Trim() function will also return Null if operated on a Null variant.
Object is a subtype of variant that can hold reference to an Object.An Object contains properties and methods. The object data type is generic and can hold a reference to any kind of object. An object is a very convenient way to represent the encompassed data and methods.
Object references store in a variable of the object data type are known as late bound. It means that object interface can not be resolve until runtime. Variables and routine parameters can be declared as a specific object type. But they are known as early bound. It means that the interface of the object was known at compile time.
A late bound variant object variable can be passed to a VBScript procedure that uses an early bound parameter.
How to Work with Object?
Dim objFSO Dim bolFilePresent Set objFSO=WSScript.CreateObject("Scripting.FileSystemObject") bolFilePresent=objFSO.FileExists("Path of the file") msgbox bolFilePresent set objFSO=Nothing
Object variables need to be destroyed when we are done with the use of those variables. Nothing is same as Null. It instructs the VBScript engine that the usage of the variable is over and it is ready to be garbage collected.
The VBScript engine destroys the object and reclaim it’s memory for other usage.This approach is safe during framework development where we need lots of objects to be created. It also helps us to reduce “fatal memory error” issue.
This is another subtype of the variant data type.It can contain result of the function or error number and description. VBscript does not really support the Error subtype and the chance of getting such variable is very minimal.
VBscript does not really support the Decimal subtype and the chance of getting such variable is very minimal.
Vbscript or UFT only support variant data type(internally it has different sub types). The process of variant to internal sub data type mapping is automatic.
However VBScript provides us ways where a coder can determine the sub types.This helps coders and VBScript to work with proper subtypes and wrong mapping side effects.
There are two types of Data coercion:
- Implicit Coercion
- Explicit Coercion
In this process, VBScript engine automatically transform variant to underlying sub types. This automatic transfer of sub types sometimes are very good and user friendly and sometimes it may fail.
When VBScript engine sees the data type and the corresponding operations, it just transfers the data type for being safer during operation. However, implicit type conversion does not happen on random basis. It just happen when we change the data of the current variable.
TypeName() is the function that can return :
In this process coders can transform a variant to one of the desired sub types.
The below are the conversion functions to explicitly data type change.
- Asc()- Returns the ANSI character of the first letter of the String.
- CBool()-Returns the Boolean value of the variable after a conversion.
- CByte()- Returns the Byte information of a variable after conversion.
- CCur()- returns the Currency information of a variable after conversion.
- CDate()-returns the Date information of a variable after conversion.
- CDbl()-returns the Double information of a variable after conversion.
- Chr()-returns the ANSI character information of a variable after conversion.
- CInt()-returns the Integer value information of a variable after conversion.
- Clng()- returns the Long value information of a variable after conversion.
- CSng()-returns the Single value information of a variable after conversion.
- CStr()-returns the String value information of a variable after conversion.
- Hex()-returns the Hex value information of a variable after conversion.
- Oct()-returns the octal information of a variable after conversion.
if VbScript is not able to convert a variable to its approved list(like conversion of an alphanumeric character to numeric one), it throws an error stating that “type mismatch”.
When we do not have control of the incoming data, it is better to use the default variant. Like the below scenarios:
- take input from users
- reading data from any database
- reading files.