6

I have assigned session a custom class's object like:

Services Obj = getServiceDetails(3); //getting all data of Service where Id = 3
Session["ServiceObj"] = Obj;

Now I want to assign its value to same class's another object in a model class. I don't know how to do it.

I tried but it is not valid way.:

Services oldObj = <Services>Session["ServiceObj"];

Pls Help me. I don't know how to do it.

asked May 29, 2013 at 6:31
3
  • 1
    Services oldObj = (Services)Session["ServiceObj"]; Commented May 29, 2013 at 6:33
  • @Igor, It would be nice if you post your comment as answer.So I can accept it. Commented May 29, 2013 at 6:37
  • Done (see my answer below) Commented May 29, 2013 at 6:42

6 Answers 6

10

Correct type cast requires round brackets:

Services oldObj = (Services)Session["ServiceObj"];
answered May 29, 2013 at 6:41
Sign up to request clarification or add additional context in comments.

Comments

2

you should use Services oldObj = (Services)Session["ServiceObj"];

instead of Services oldObj = <Services>Session["ServiceObj"];

answered May 29, 2013 at 6:35

Comments

1
not <Services> use (Services) for casting
answered May 29, 2013 at 6:37

Comments

1

Cast it with your Class like this

Services obj = (Services)Session["ServiceObj"];
Sachin
41.1k7 gold badges94 silver badges107 bronze badges
answered May 29, 2013 at 6:38

Comments

1

You can also refactor the typed data retrieval using a generic, e.g. using an extension method, like so:

public static class MyExtensions
{
 public static T GetTypedVal<T>(this HttpSessionState session, string key)
 {
 var value = session[key];
 if (value != null)
 {
 if (value is T)
 {
 return (T)value;
 }
 }
 throw new InvalidOperationException(
 string.Format("Key {0} is not found in SessionState", key));
 }
}

Which you can then use for reference and value types, like so:

 Session["Value"] = 5;
 var valResult = Session.GetTypedVal<int>("Value");
 Session["Object"] = new SomeClass() { Name = "SomeName" };
 var objResult = Session.GetTypedVal<SomeClass>("Object");
answered May 29, 2013 at 6:58

Comments

0

to get value from session you should cast it.

Services oldObj = (Service)Session["ServiceObj"];
answered Jul 5, 2020 at 16:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.