Introduction
I started doing some MVC stuff, and came up with another way that doesn't involve any outward-facing casting to the object's type, AND preserves the strong typing that we all know and love in real programming languages:
Using the Code
I set up a static
class called SessionVars
that contains a property for each variable.
public static class SessionVars
{
public static HttpSessionState Session
{
get
{
return System.Web.HttpContext.Current.Session;
}
}
public static string MyStringVar
{
get
{
string value = string.Empty;
if (SessionVars.Session != null)
{
object obj = SessionVars.Session["myStringVar"];
value = (obj == null) ? default(string) : (string)obj;
}
}
set
{
SessionVars.Session["myStringVar"] = value;
}
}
}
Keep in mind that this doesn't remove the need for casting, it simply abstracts it away so you can do the following in your code:
string myValue = SessionVars.MyStringVar;
Which is a lot cleaner than doing it this way:
string myValue = (string)(System.Web.HttpContext.Current.Session["myStringVar"]);
You also don't have to worry about how the variable key was spelled, because that's all handled in the property that you defined.
One final note - .NET Core handles the session state quite differently, and while this code won't work in .NET Core, all you have to do is change the property that returns the session state to do it the Core way, and all of the other properties should theoretically work without changes.