4 out of 12 rated this helpful - Rate this topic

How to: Read Values from Session State

This example accesses the Item property to retrieve the values in session state.

string firstName = (string)(Session["First"]);
string lastName = (string)(Session["Last"]);
string city = (string)(Session["City"]);

This example requires:

  • A Web Forms page or class that has access to the current request context using the Current property in an ASP.NET application that has session state enabled.

No exception is thrown if you attempt to get a value out of session state that does not exist. To be sure that the value you want is in session state, check first for the existence of the object with a test such as the following:

if (Session["City"] == null) 
    // No such value in session state; take appropriate action.

If you attempt to use a nonexistent session state entry in some other way (for example, to examine its type), a NullReferenceException exception is thrown.

Session values are of type Object. In Visual Basic, if you set Option Strict On, you must cast from type Object to the appropriate type when getting values out of session state, as shown in the example. In C#, you should always cast to the appropriate type when reading session values.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Calling with default value
I'm using this, since I usually want that bool (or any other), stored or not

bool b = (bool) (Session["IsValid"] ?? false);  // false is default value
The advice is true for any nullable object.

It is true of any nullable object. Strings are nullable, bool, int, double are not (there is an alternative).

This is the quick test:

bool b = null; // Compiler error: Cannot convert null to 'bool' because it is a non-nullable value type

Alternative for non-nullable objects:

Nullable<bool> b = (Nullable<bool>)Session["loggedin"];

Then you can check for true, false, or null.

There are exceptions to this advice
So why is true of strings but not of int, bool, or double? Try this: bool b = (bool) Session["loggedin"]; This causes a NullReferenceException as does casting to an int or double for the respective data types. Are strings somehow special or different?