This post comes as an extension to a post by Shlomo Goldberg (in Hebrew) that talks
about how to work with session variable in a safer way than plain strings.
Shlomo Goldberg has suggested that instead of strings we should work with enum entries.
This way is more efficient for developers who can simply find all the uses of a certain session
variable and can find all reference to it.
As you can see from the code attached to that post, it uses indexer with SessionParam
enum using a private method called RetrieveFromSession, which calls it’s overloading
method that accepts the good old string parameter (using the enum.ToString method).
This one, of course holds some performance penalty because it’s use of the ToString method
call for enum. Here’s another approach:
As an extension for this suggestion one might suggest the use of properties that envelopes
the session variable within.
All properties are in a class (The same as in the class suggested by Shlomo Goldberg, only doesn't have to be singleton)
A property of such can look like that:
1: public UserInfo DelegatingUser
5: return Session != null ? (UserInfo)Session[DELEGATING_USER] : null;
9: if (Session != null)
11: Session[DELEGATING_USER] = value;
Where Session is also a property envelopes HttpContext.Current.Session
and the DELEGATING_USER is a string constant
What do we gain from it?
1. Type safety. Use of this kind of properties will prevent override one type of an object by
another without the compiler will notify.
2. We don’t have to use the enum.ToString anymore and therefore gain our performance
back almost fully.
3. We can add logic to the properties.
There are two (or more) downsides however:
1. This class may be coupled to the project’s data model, you cannot simply put it on another
project because it won’t compile.
2. You cannot add session variables through this class form another files. Adding new session
variables requires adding new properties to the class.
You can download the class in here. (Note – it won’t compile because it is coupled to
my project’s data model)