Click here to Skip to main content
15,890,982 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
in my web page , I put that code

C#
static int x = 1;
protected void Page_Load(object sender, EventArgs e)
{
    Response.Write(x++);
}


and I get increase in X value

but without static it doesn't.

C#
int x = 1;
protected void Page_Load(object sender, EventArgs e)
{
    Response.Write(x++);
}


where does it store the value?
how exactly does it work?
please.
Posted

1 solution

Don't rely on it.

static means that there is a single instance of the variable and that it is shared by all class instances. In your case, it is being preserved across pages, because the instance of the application that holds it has not been terminated and unloaded by the server between page load operations. This is not guaranteed, and cannot be relied upon. It may also be affected by other users who reference the same pages.

If you need to preserve server values across pages, then do not use static - it will cause you unpredictable results in production which will be very, very difficult to track down and fix. Use Session variables[^] instead, as these are both designed to hold data across pages, and individual to each user.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900