Dhwani
Dhwani

Reputation: 7626

How to get Session's value in a class object?

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.

Upvotes: 6

Views: 12285

Answers (6)

Ah Sa Fa
Ah Sa Fa

Reputation: 181

to get value from session you should cast it.

Services oldObj = (Service)Session["ServiceObj"];

Upvotes: 0

StuartLC
StuartLC

Reputation: 107247

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");

Upvotes: 1

Ali Shahbaz
Ali Shahbaz

Reputation: 845

Cast it with your Class like this

Services obj = (Services)Session["ServiceObj"];

Upvotes: 1

Igor
Igor

Reputation: 15893

Correct type cast requires round brackets:

Services oldObj = (Services)Session["ServiceObj"];

Upvotes: 10

Kamil A.
Kamil A.

Reputation: 61

not <Services> use (Services) for casting

Upvotes: 1

Taj
Taj

Reputation: 1728

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

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

Upvotes: 2

Related Questions