views:

108

answers:

2

Is it better practice to use class variables, or the session cache in ASP.NET? I have a variable which I need to persist across page loads. Is it better to use:

public class MyClass {
  private SomeObject anObject;
  private method1() {
    anObject = new SomeObject();
  }
  private method2() {
    // do something with anObject
  }
}

or

public class MyClass {
  private method1() {
    Session["anObject"] = new SomeObject();
  }
  private method2() {
    SomeObject anObject = (SomeObject)Session["anObject"];
  }
}
+2  A: 

Use cache. I'm not working on .NET, but in Java with servlets. There I would definitely use HTTP session, since my application can run in a cluster of servers and I know that storing a value in HTTP session will work in this setup, while storing it in class variable might be a bit problematic. You can store the whole class MyClass in HTTP session and then you can have values stored in class variables.

Basically, you can view HTTP sessions like a hashtable.

kovica
A: 

They both seem to work, so I'll stick with the cache then. Thanks :)

Echilon