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.
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.
My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.