What is variant?
A Variant is the only variable type provided in the
VBScript scripting engine for ASP. Although variants don't have
most efficeint use of memory and require extra processing compared
to the more usual base data types such as Integer, variants do have
their own advantages: Variants automacally handle implicit type
conversion, which permit to ignore the difference among base data
types. For example, we can use a variant storing String as an Integer
as needed.
Example 1: using typename to return a variant subtype
<html>
<head>
<title>Using TypeName</title>
</head>
<body>
<%
Dim dblPi,whatisPi,datToday, whatisDate,strText,whatisText
dblPi=3.12415926
whatIsPi=TypeName(dblPi)
datToday=Date
whatIsDate=TypeName(datToday)
strText="Hello World"
whatIsText=TypeName(strText)
Dim emp
emptyVar=TypeName(emp)
%>
<P><b>dblPi returns <%=whatIsPi%></p>
<p>datToday returns <%=whatIsDate%></p>
<p>strText returns <%=whatIsText%></p>
<p> emp return <%=emptyVar%></b></p>
</body>
</html>
How is works:
Alghough each variable is defined by default as a variant, it assumes
the subtype of the data that is stored in it. Hence when the code
is executed it returns Double, Date, String and Empty. Rember vbscript
is not case sensitive.
The above code return like :
dblPi returns Double
datToday returns Date
strText returns String
emp return Empty
Example 2: Converting varants from one subtype to another
It will often be the case that you will need to read in data as
a string, then perform numerical operations on it. In order to do
this, you will need bo convert the data from a string data type to
a double. Using functions, Cint,CSng,Cstr we can convert between
numeric and string datatypes.
<html>
<head>
<title> Converting Variants</title>
</head>
<body>
<% Dim strPi, dblPi,intPi,strPi2,whatisPi1,whatisPi2,whatisPi3,whatisPi4
strPi="3.1415926"
whatisPi1=TypeName(strPi)
dblPi=cdbl(strPi)
whatisPi2=typename(dblpi)
intpi=Cint(dblPi)
whatisPi3=TypeName(intPi)
strPi2=Cstr(intPI)
whatisPi4=typename(strPi2)%>
<p><B>Pi is a <%=whatispi1%> and Pi returns <%=strpi%></b></P>
<p><B>Pi is a <%=whatispi2%> and Pi returns <%=dblPi%></b></P>
<p><B>Pi is a <%=whatispi3%> and Pi returns <%=intPi%></b></P>
<p><B>Pi is a <%=whatispi4%> and Pi returns <%=strPi2%></b></P>
</body>
</html>
How it works:
strPi is initially a string subtype. The statement:
dblPi=CSng(strpi) changesi ti to Single subtype and saves the result
in dblPI.
Similarly for the other statement.
|