Global variables are useful in ASP.NET. They don't 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.
/// Contains my site's global variables.
public static class Global
/// Global variable storing important stuff.
static string _importantData;
/// Get or set the static important data.
public static string ImportantData
_importantData = value;
Discussion. 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. Here are some questions that can be answered by testing.
Global Static fields and properties in ASP.NET are always global. Another copy is never created. You will not have duplication.
Performance Static fields are efficient in normal situations. You will only have one copy of the data and there is no locking required.
Application The Application collection can be used the same way as static variables. But it may be slower and harder to deal with.
Global variable example 2: C#
public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
// Get the current ImportantData.
string important1 = Global.ImportantData;
// If we don't have the data yet, initialize it.
if (important1 == null)
// Example code.
important1 = DateTime.Now.ToString();
Global.ImportantData = important1;
// Render the important data.
Important1.Text = important1;
With static fields, casting is not required. A problem with the Application object in ASP.NET is that it requires casting to read its objects. This introduces boxing and unboxing. Static fields allow you to use generics.
Is this recommended? Yes, and not just by the writer of this article. It is noted in Professional ASP.NET by Apress and many sites on the Internet. It works well—but don't take my word for it.
You can initialize the class at startup—put the code in the Application_Start event in Global.asax. Alternatively, use a static constructor or logic to lazily initialize the class.
Summary. We used static classes and variables to store site-wide objects in memory. This is a recommended practice on ASP.NET websites. It is possible to make your code easier to read and safer to use with globally scoped, static variables.