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:
- All tests to determine whether a Session variable has been set are of the form
IsEmpty(Session("myVar"))
- All session variables are
Remove
d and not set= ""
?
Empty
is a strange beast: it is simultaneously equal to both""
and0
. Seriously, try it:It'll write out "True".
This means that testing for
Not IsEmpty(myvar)
is equivalent to testingmyvar <> ""
, butIsEmpty(myvar)
is not equivalent tomyvar = ""
. 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
andIsNull
and whatnot, and just using the& ""
"hack":This'll transparently handle Nulls and Empties without you needing to write a whole bunch of code.
No, it could be not safe. Perhaps you need to use functions:
IsNull
,IsEmpty
andVarType
Please take a look at What is the '<>' asp operator?