jpaugh
jpaugh

Reputation: 7035

How long does an object in the CodeBehind live?

If I create an object in the code-behind of an .aspx page, how long can I expect that object to live? Will it live across post-backs? Could I pass it somehow to another page? Could I make it live as long as, say, the session object?

I searched the web hoping for a document explaining the life-cycle of objects created from the code-behind, and how to interact with this life-cycle; any related links would be appreciated.

By the way, I am using C# in the code-behind, but I imagine most advice targeting VB would be applicable as well.

Upvotes: 2

Views: 518

Answers (3)

Leons
Leons

Reputation: 2674

The code-behind lives for the duration of the request. It will not live across post-backs. You can add values to Session if you want it across a postback. The same would apply to VB.

Upvotes: 3

Jakob Gade
Jakob Gade

Reputation: 12419

The object will only live as long as the page, i.e. for the duration of the page request. If you want to make it live longer you can store in the Session and retrieve it for each request.

Upvotes: 5

BrokenGlass
BrokenGlass

Reputation: 160852

If I create an object in the code-behind of an .aspx page, how long can I expect that object to live? Will it live across post-backs? Could I pass it somehow to another page? Could I make it live as long as, say, the session object?

You can save object instances within the session:

Session["Foo"] = new MyFoo();

You can retrieve the instance on any page that has access to the session:

MyFoo foo = (MyFoo) Session["Foo"];

An alternative to this is using a static variable - in this case the variable keeps its value until the app domain gets destroyed (i.e. when IIS is restarted) - but it is also global in the sense that it has the same value for all users (since its not related to the session at all).

Upvotes: 5

Related Questions