On my login web page (i.e. the first page the user hits) I have code of this form:
public class MyPage : System.Web.UI.Page {
private MyClass _obj = new MyClass();
...
MyClass
has the constructor:
public MyClass() {
var sess = HttpContext.Current.Session; // no problem here
sess["MyValue"] = 123; // throws null ref exception coz sess is null
}
As I've commented, the call to sess["MyValue"]
throws a null reference exception, because the HttpContext hasn't yet created the session object.
So when is it safe to start accessing the Session object? I don't want to give up on the inline declaration/initialization of _obj
; that's very convenient for me! What alternatives do I have?