For one of the innumerable personal apps I am writing, I decided to store some values in session variables. However, I loathe the syntax for both getting and setting such variables:
Session["UserID"] = userID;
GetSomeData(Convert.ToInt16(Session["UserID"]));
Yuck. Why? The literal strings. I want strongly-typed stuff. I don't want to have the opportunity to accidentally type Session["UsrID"] and deal with resulting issues (I know, it is not that big of a deal, but you know), I want design-time features like code completion/Intellisense. So, at first my idea was to create an enum containing all of the session variables I would use for the app, like so:
public enum SessionVariables
{
UserID, ClientID, etc.
}
And then I would do this:
Session[SessionVariables.UserID.ToString()] = userID;
That gave me Intellisense and strong typing (more so than a string literal), reducing the chance that something would be typed incorrectly.
But I still don't like the whole "Session[...]" thing. In order to understand my solution, I first must say that I have created a base class for my site's pages. Every ASP.NET page must inherit from the System.Web.UI.Page class at some point, either directly or as a result of a deeper inheritance structure, and I have an intermediate class which inherits from that class, and then all of my pages inherit from that derived class. So, the solution I came up with (I doubt this is in any way original, nor do I feel it is necessarily the ideal) involves creating properties on that base class. For example:
public short User_UserID
{
set
{
Session["UserID"] = value;
}
get
{
return short.Parse(Session["UserID"].ToString());
}
}
As long as the page inherits from this intermediate base class instead of inheriting directly from the Page class, I have an easy, strongly-typed means of obtaining session variables without using the nasty syntax (I only need to use it in the property). So, now I can do this in my code-behind files:
User_UserID = userID;
GetSomeData(User_UserID);
Much sexier, and as an added bonus it abstracts WHERE I store the variables. So, if I want to, I can change that property in the base class so that instead of storing this value in session, I can store and retrieve it from a cookie should I desire to do so. (By the way, the reason I preface the property with the "User_" is because it makes it gives the property name a context, in this case these are properties associated with the current User. Also, one of the variables I am storing is a ClientID and that is already the name of a property of the Page class, so I have a collision there.)
Now, the question I have is this: is this a good way to accomplish this? It works, and I personally like it, but I have only thought it through for about 25 minutes.