Hi!
In most of ourweb applications, we (must) use the session object, which gives us better way of data storing (session object lives over the HTTP protocol and exists all over the user's session lives {except of expiration etc...}).
The access to the session objects and variables is quite easy and simple, BUT, what happens when you want to store your complex struct or object in the session (even some other system object)? THEN, you must cast this session variable, and check if it alives before you can access its properties etc...
I have a good suggestion that also will encapsulate the sesison's variables and will be easy to manage, pay attention:
Firstable, I created a static class, called: Repository, which will expose the session variables as properties, and the access to these objects will be much more easy and explicit.
The repository static class:
public static class Repository
{
public static SomeObject SessionSomeObject
{
get
{
return HttpContext.Current.Session["SomeObject"] as SomeObject;
}
set
{
HttpContext.Current.Session["SomeObject"] = value;
}
}
// Some more properties declarations
}
(This class gathers all the session/application members = good and convenient code management).
NOW, look at the 'old fashioned' and regular way that the sytax suggests us (if we don't use the Repository static class):
if (Session["SomeObject"] != null)
{
myObject = ((SomeObject)Session["SomeObject"]).MyProperty;
}
else
{
// bla bla bla...
}
In the above example, we must check if the object is alive in the session firstly if we want to access its properties (unless we do it, it will throw us a runtime error). In the bottom example we cover this case with one sentense of code:
myObject = Repository.SessionSomeObject.MyProperty;
Here, even if the object is null, it will we create an instance of it and will return us some default value of the object's property.
Have a good day...
p.s.
This code relates also to the Application object!