Tuesday, April 06, 2010

ASP: Determining Variable Types with TypeName Function

If you've been working in ASP for any length of time, you know you don't have to type variables. You just declare them using the DIM statement. Heck, you don't even have to declare them if you don't want to (but I don't recommend it).

But what if you're perofmring some sort of calculation on a variable, or you're doing some sort of boolean check after manupulating it or getting a value from a database? Or you want to put it into a database field that's been typed and you don't know if it matches and you need to convert it first?

Well here's a handy function you can use to determine what type of varient the actual value of the variable is: TypeName()

It works like this:
var = 1
Reponse.write TypeName(var)
In this case, the output would be
I've found this to be especially handy when dealing with values being returned from a database or when validating variable type to prevent an SQL injection attack.

Let's say I'm using a QueryString variable to pass a record id to a page, and then I use that id to pull a record from the database. So my URL might look like:
In this case I can validate it by
intRecordID = Request.QueryString("rid")
If TypeName(intRecordID) = Integer Then....
It's also handy when telling the differnece between NULL and an Empty String. Anyone who's done development knows that just because there's nothing in the variable doen't mean it's actually empty, since NULL and Empty are treated differently.
If TypeName(TheVar) = Empty then...
If TypeName(TheVar) = NULL Then...
Handy, especially whn doing some sort of conditional aggregate of data from a database pull where you're combining things.

Here's a list of all the different types than can come back:

Long Integer
Date String

1 comment:

Watch TV Shows said...
This comment has been removed by a blog administrator.