ASP.NET C# Static Variables are global? ASP.NET C# Static Variables are global? asp.net asp.net

ASP.NET C# Static Variables are global?


Yes, in ASP.NET a static fields lifetime is for the app domain (note that this differs a bit for generic types).

I'd recommend using the server Session for storage of data you want to associate with an instance of a client browser session (user login).i.e.

Session["_groupID"] = Convert.ToInt16(Request.QueryString["GroupID"]);

you can retrieve it by doing:

short groupID = Convert.ToInt16(Session["_groupID"]);


It's incorrect to say that a static variable exists application wide. They in fact exist at two different levels

  1. For non-generic types there is a single static variable per AppDomain
  2. For generic types there is one per generic instantiation per AppDomain

An application can contain many AppDomains and is true in several types of applications.

If you want to store user specific settings though, use a Session variable.


Static variables has the same lifetime as an application domain they were created in. So if you get some wrong values it can be some problems in the application logic or else. You should use SessionState for per-user data.