代码改变世界

Global Variables Example

2012-03-08 12:13  barbarossia  阅读(590)  评论(0编辑  收藏  举报

You want to store global variablesin your ASP.NET site. Global variables don't need to be copied and only one is needed in the website application. We can use static properties to store single instance data.

Overview:This ASP.NET example shows how to use global variables in web sites. It uses C# code.

Global variables

Example

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. Right-click on your project name and select "Add ASP.NET Folder" -> App_Code. Here is the code you can put in the class file.

Global variable example 1 [C#]

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;
	}
    }
}

Creating your static class.In your App_Code folder, right click and Add New Item. Inside the new class, change the auto-generated code and type or insert a static class such as this one:

Description of the Global class. It is static. Static means it is only created once for the type. You can name the class anything, not just Global. It contains important data. The _importantData field and ImportantData property are for example. Rename them to your liking.

Property Examples

Data types in example.The class contains string types. Here we can have any value or reference type. Not just string, but int, List or Dictionary. It has a property. The "get" and "set" keywords mean you can access the field variable through the property.

Static variables usage

Here we want to use the static global variables in the class. Open your web page's code behind file. It is named Default.aspx.cs usually.

Global variable example 2 [C#]

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 only.
	    important1 = DateTime.Now.ToString();
	    Global.ImportantData = important1;
	}

	// 3. // Render the important data.
	Important1.Text = important1;
    }
}

Description of ASP.NET web form. It accesses the global variable. The first thing Page_Load does is get the static data. This example initializes the global variable if it isn't initialized yet. It then writes the value of Global.ImportantData to the literal.

asp:Literal Use

Test your static data

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. Next, here we see some questions that can be answered by testing.

Question and answer

Is the data global? Yes, static fields and properties in ASP.NET are always global. Another copy will never be created, so you will not have duplication.

Singleton Pattern Versus Static Class

Are static fields efficient?Yes, in normal situations. You will only have one copy of the data and there is no locking required. In my experience they are thread-safe.

What about the Application object?The Application[] collection is a throwback to classic ASP. It can be used the same way as static variables, but it may be slower and harder to deal with.

Is casting required?No. 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 like List or Dictionary.

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.

Can I initialize the class at startup?Yes. Put the code in the Application_Start event in Global.asax. Alternatively, use a static constructor. Another option is to use logic to lazily initialize the class.

How can I nest instance classes?You can nest objects in your static App_Code class. Mark their declaration with static, and use the class as normal.

Summary

Here we saw how you can use static classes and variables for an efficient and clear way to store site-wide objects in memory. Make your code easier to read and safer to use with globally scoped, static variables.