cnd
cnd

Reputation: 33764

Can I have static property per session?

I've got partial class as code-behind for my form where I have

private object x;

And I'm trying to use it on Page_Load

protected void Page_Load(object sender, EventArgs e) {
    if (x != null)
        y = x;

first time it's null but then by clicking an element in TreeView I set it to some object and it's not null there. It shows on form.

When I'm trying to work with object in web form, form is processing Page_Load again and x is null there. How can I keep x static for each open session?

Upvotes: 1

Views: 167

Answers (1)

Craig Brett
Craig Brett

Reputation: 2340

As far as I know, static won't remain for the session between requests. You'd probably want to make use of the Session dictionary here. It's something that comes in on all code-behind page files.

Session["x"] = 10;
// if you want you can do:
// var x = Session["x"];
if (!String.IsNullOrEmpty(Session["x"]))
{
    y = Session["x"];
}

The code above doesn't take into account casting x. So if y is an int, you could do this in the if block:

// imagine there's some type safety checks somewhere, yada yada
y = Convert.ToInt32(Session["x"]);

This keeps variables for the lifetime of the session. To prove a point, try doing this in 2 different browsers at the same time. They'll both keep different values for x.

Hope this helps.

Upvotes: 3

Related Questions