user249375
user249375

Reputation:

Get a session back from a class in another class

I have a class where i am setting and getting a session. I am fairly new to C# How can i retrieve a session from my class in another class?

Here is my session class.

public class JobApplicantSession
{

    public JobApplication ApplicationSession
    {

           get
       {
           JobApplication _application = (JobApplication)HttpContext.Current.Session["Application"];

           return _application;

        }
      set
        {
            HttpContext.Current.Session["Application"] = value;
         // Session["Application"] = value;
       }
    }

I am able to set the session. However, getting it i dont know how. I made an object of the class and the object can access the function name ApplicationSession

JobApplicantSession sess = new JobApplicantSession();
sess.ApplicationSession

I know it probobly depends on what i need to do with it, but i just wanted to verify its setting and getting properly

Upvotes: 0

Views: 926

Answers (1)

Adrian Iftode
Adrian Iftode

Reputation: 15673

The getter will throw an exception when there is nothing in session so you need to deal with this.

So you need to check if the session value exists

get
{
  if ( HttpContext.Current.Session["Application"] != null )
    return (JobApplication)HttpContext.Current.Session["Application"];
  return null;
}
set
{
   ...
}

You might not use the setter at all..

get
    {
      if ( HttpContext.Current.Session["Application"] == null )
          HttpContext.Current.Session["Application"] = new JobApplication();
      return (JobApplication)HttpContext.Current.Session["Application"];
    }

Or..

 get
        {
          if ( HttpContext.Current.Session["Application"] == null )
              HttpContext.Current.Session["Application"] = JobApplicationFactory.CreateApplication();
          return (JobApplication)HttpContext.Current.Session["Application"];
        }

Where JobApplicationFactory might be a class which creates a JobApplication object

EDIT I realized I didn't answer the question..

To call the getter from another class..

public class JobApplicant
{
   private JobApplication application;
   public void AddCurrentApplication()
   {
       var jas = new JobApplicationSession();
       application = jas.ApplicationSession;
   }
}

Upvotes: 2

Related Questions