-1

I want to how to assign the session variable, which is of the type of a class I have define, Here OrderData class. I get error on 'Session["MyOrder"];'

My code snippet it like below. Also as ord will be a reference to the object, Any change to the object will be reflected to the session object?

OrderData ord = new OrderData();  
if (Session["MyOrder"] == null)
{
    Session.Add("MyOrder", ord);
}
else
{
    ord = Session["MyOrder"];
}
MethodMan
  • 18,625
  • 6
  • 34
  • 52
coder
  • 122
  • 1
  • 13

1 Answers1

2

You have to explicitly cast it to your type like:

ord = Session["MyOrder"] as OrderData;

and then check for null. as could return null if the casting fails.

if(ord != null)
{
   //valid value
}

You can also use:

ord = (OrderData) Session["MyOrder"];

But this could throw an exception in case your Session holds a different type than OrderData

For:

Also as ord will be a reference to the object, Any change to the object will be reflected to the session object?

Since `objects are instances of a class, a reference type, they will point to the same instance.

Consider the example below:

OrderData ord1 = new OrderData() {ID = 2};
Session["MyOrder"] = ord1;

var ord2 = Session["MyOrder"] as OrderData;
ord2.ID = 1;

at the end of code execution both ord1 and ord2 will have ID as 1, as both references points to the same object.

Habib
  • 219,104
  • 29
  • 407
  • 436
  • if you are worried about throwing an exception then why not do the following to safely check `if (!string.IsNullOrEmpty(Session["MyOrder"] as string))` ? – MethodMan Feb 10 '15 at 19:25
  • 2
    @MethodMan, `MyOrder` is not a string, there is no need to convert it to a string and then check using `String.IsNullOrEmpty`. Casting it against *particular type* using `as` and then checking against `null` is sufficient. – Habib Feb 10 '15 at 19:27
  • If you look at the `OP` second line of code in his question what I have commented on is what it was in reference to, prior to your multiple updates to your answer.. the `OP` is checking is the session is null way before adding the Object to the Session – MethodMan Feb 10 '15 at 19:30
  • @MethodMan, Are you saying to use *your* `string.IsNullOrEmpty` check to see if the key exists in the Sesion, instead of this check `if (Session["MyOrder"] == null)` ? – Habib Feb 10 '15 at 19:38
  • we had this discussion before..many ways to do this - http://stackoverflow.com/questions/234973/what-is-the-best-way-to-determine-a-session-variable-is-null-or-empty-in-c cheers – MethodMan Feb 10 '15 at 19:40