Often we want to use globals in ASP.NET. These do not need to be copied and only one is needed in the website application.
We use static
properties (in the C# language) to store this single instance data. In testing, statics work well for global data.
First, older versions of ASP used the Application[]
object, but this is inefficient in ASP.NET. To get started in adding your static
global variables in ASP.NET, create the App_Code
folder.
App_Code
. Here is the code you can put in the class
file.class
is static
. This means it is only created once for the type. You can name the class
anything, not just Global.class
contains string
types. Here we can have any value or reference type—not just string
, but int
, List
or Dictionary
.using System; using System.Data; using System.Linq; using System.Web; /// <summary> /// Contains my site's global variables. /// </summary> public static class Global { /// <summary> /// Global variable storing important stuff. /// </summary> static string _importantData; /// <summary> /// Get or set the static important data. /// </summary> public static string ImportantData { get { return _importantData; } set { _importantData = value; } } }
Here we want to use the static
global variables in the class
. Open your web page's code-behind file. It is usually named Default.aspx.cs
. This web form accesses the global variable.
Page_Load
first gets the static
data. This example initializes the global variable if it isn't initialized yet.Global.ImportantData
to the literal. This is rendered to the browser.using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // 1. // Get the current ImportantData. string important1 = Global.ImportantData; // 2. // If we don't have the data yet, initialize it. if (important1 == null) { // Example code. important1 = DateTime.Now.ToString(); Global.ImportantData = important1; } // 3. // Render the important data. Important1.Text = important1; } }
Now run your web page and you will see that the global variable is used. This global data will only be run once for your entire application, saving lots of resources.
static
variables. But it may be slower and harder to deal with.static
fields, casting is not required. A problem with the Application object in ASP.NET is that it requires casting.You can initialize the class
at startup—put the code in the Application_Start
event in Global.asax. Alternatively, use logic to lazily initialize the class
.
We used static
classes and variables to store site-wide objects in memory. This is a recommended practice. Static variables can make code easier to read and more robust.