What is the best way to check for the existence of a session variable in ASP.NET C#?
I like to use String.IsNullOrEmpty() works for strings and wondered if there was a similar method for Session. Currently the only way I know of is:
var session; if (Session['variable'] != null) { session = Session['variable'].ToString(); } else { session = 'set this'; Session['variable'] = session; }
To follow on from what others have said. I tend to have two layers:
The core layer. This is within a DLL that is added to nearly all web app projects. In this I have a SessionVars class which does the grunt work for Session state getters/setters. It contains code like the following:
Note the generics for getting any type.
I then also add Getters/Setters for specific types, especially string since I often prefer to work with string.Empty rather than null for variables presented to Users.
e.g:
And so on…
I then create wrappers to abstract that away and bring it up to the application model. For example, if we have customer details:
You get the idea right? 🙂
NOTE: Just had a thought when adding a comment to the accepted answer. Always ensure objects are serializable when storing them in Session when using a state server. It can be all too easy to try and save an object using the generics when on web farm and it go boom. I deploy on a web farm at work so added checks to my code in the core layer to see if the object is serializable, another benefit of encapsulating the Session Getters and Setters 🙂