Static variable in asp.net page

Ashwani K picture Ashwani K · Mar 7, 2011 · Viewed 18.4k times · Source

I am having one doubt regarding the use of static variable in Asp.net pages.

I am having one page say UserDetails.aspx. In this page, I have one static variable to store some data specific to a user. So, will this variable be shared across multiple user or a separate variable will be created for each user?

  public partial class UserDetails : System.Web.UI.Page
    {
       static int numberOfReviews=0;
       protected void Page_Load(object sender, EventArgs e)
         {
            numberOfReviews= GetReviews();
         }
    }

Here, will numberOfReviews be specific to each user or will be shared?

numberOfReviews

Answer

Unmesh Kondolikar picture Unmesh Kondolikar · Mar 7, 2011

Application Scope: The variables that have application scope are available throughout the application, i.e to all users of the applications across all pages.

Session Scope: When many users connect to your site, each of them will have a separate session (tied to the identity of the user that is recognized by the application.) When the variable has session scope it will have new instance for each session, even though the users are accessing the same page. The session variable instance is available across all pages for that session.

Page Scope: When you have a instance variable on a Page it is specific to that page only and that session only.

Static variables have Application scope. All users of the application will share the same variable instance in your case.

Please note that although static variables have one instance in the app domain. So if you have your application deployed on a load balanced web farm, each app domain will have a separate instance of the variable. This might give you incorrect result.

Based on this you should decide what scope your variable should be in. IMO, using static variables is a code smell and should be discouraged.