In ASP an uninitialized Session variable Is Empty. I know that the correct way to check for a Session value, and remove a value, is the following:
IF NOT IsEmpty(Session("myVar")) THEN
' Go ahead and use Session("myVar")
...
' Now if we're all done with myVar then remove it:
Session.Contents.Remove("myVar")
END IF
I've inherited a codebase where Application and Session variables are typically set = ""
after use, and all tests for a value are of the form (Sessions("myVar") = "")
. This test appears to work when the Session variable has not been declared ... or maybe it's just working by dumb luck.
Is it safe to use comparison with the empty string to test for a Session variable? I.e., is the following "practically as good" as the correct method shown above?
IF Session("myVar") <> "" THEN
' Go ahead and use Session("myVar")
...
' Now if we're all done with myVar then blank it:
Session("myVar") = ""
END IF
Or should I refactor the codebase so that:
IsEmpty(Session("myVar"))
Remove
d and not set = ""
?Empty
is a strange beast: it is simultaneously equal to both ""
and 0
. Seriously, try it:
dim x, y, z
x = Empty
y = ""
z = 0
Response.Write (x = y) AND (x = z)
It'll write out "True".
This means that testing for Not IsEmpty(myvar)
is equivalent to testing myvar <> ""
, but IsEmpty(myvar)
is not equivalent to myvar = ""
. Whether that mostly-theoretical difference bothers you or not is something only you can answer, but personally, I wouldn't waste time on refactoring.
If you do decide to refactor, I would suggest forgetting about IsEmpty
and IsNull
and whatnot, and just using the & ""
"hack":
If Session("myvar") & "" <> "" Then
This'll transparently handle Nulls and Empties without you needing to write a whole bunch of code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With