C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: Right-click on your project name and select "Add ASP.NET Folder" and then App_Code. Here is the code you can put in the class file.
Static: The Global class is static. This means it is only created once for the type. You can name the class anything, not just Global.
Tip: The class contains string types. Here we can have any value or reference type—not just string, but int, List or Dictionary.
Also: It has a property. The "get" and "set" keywords mean you can access the field variable through the property.
PropertyGlobal 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;
}
}
}
And: Page_Load first gets the static data. This example initializes the global variable if it isn't initialized yet.
Then: It writes the value of Global.ImportantData to the literal. This is rendered to the browser.
asp LiteralGlobal 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.
important1 = DateTime.Now.ToString();
Global.ImportantData = important1;
}
// 3.
// Render the important data.
Important1.Text = important1;
}
}
Global: Static fields and properties in ASP.NET are always global. Another copy is never created. You will not have duplication.
Singleton, StaticPerformance: 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.