Search code examples
c#sessionobjecthttpcontext

How to print values of C# session object


I am saving some values in session as below.

List<MyEntity> MyVariable = <some values here>;
System.Web.HttpContext.Current.Session["MySession"] = MyVariable;

When I try to print MySession variable in Immediate Window then it displays following:

Count = 2
    [0]: {MyProject.Model.MyEntity}
    [1]: {MyProject.Model.MyEntity}

How do I print the values which are inside these indexes 0 and 1? I tried the following but it didn't work as it shows error "Cannot apply indexing with [] to an expression of type 'object'":

System.Web.HttpContext.Current.Session["MySession"][0];

Solution

  • You have to cast your value to the type you assigned, and apply the index on that :

    ((List<MyEntity>)System.Web.HttpContext.Current.Session["MySession"])[0];
    

    The Session only hold the generic type Object for all values, you have to cast them to the correct type each time you access it. To avoid casting at multiple places, you can create a wrapper class around Session, as seen in this answer.