apocalypse
apocalypse

Reputation: 5884

Access to a Session object

Why I can access Session object in Page_Load method in instance of System.Web.UI.Page, but I can't do it in other places?

  public partial class Statystyki : System.Web.UI.Page
  {
        // Session object not allowed here


        protected void Page_Load (object sender, EventArgs e)
        {
              // but allowed here
        }
  }

And not allowed in custom classes. How to get reference to this object from own class?

Upvotes: 1

Views: 1608

Answers (3)

BrokenGlass
BrokenGlass

Reputation: 160852

At its core the error you get has nothing to do with page life-cycle - simply field initializers are not allowed to access other fields/properties of the object that is being created.

From the C# spec - 10.5.5.2 Instance field initialization:

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name. In the example class A { int x = 1; int y = x + 1; // Error, reference to instance member of this } the variable initializer for y results in a compile-time error because it references a member of the instance being created.

Upvotes: 2

TGH
TGH

Reputation: 39248

You can access it in custom classes like this

HttpContext.Current.Session["Key"]

Upvotes: 3

Mike
Mike

Reputation: 1974

The Session property is set after the Page object is constructed page lifecycle.

Upvotes: 2

Related Questions