How can I set a global variable in a C# web application?
What I want to do is to set a variable on a page (master page maybe) and access this variable from any page.
I want to use neither cache nor sessions.
I think that I have to use global.asax. Any help?
This question is related to
c#
.net
global-variables
I second jdk's answer: any public static member of any class of your application can be considered as a "global variable".
However, do note that this is an ASP.NET application, and as such, it's a multi-threaded context for your global variables. Therefore, you should use some locking mechanism when you update and/or read the data to/from these variables. Otherwise, you might get your data in a corrupted state.
/// <summary>
/// Contains global variables for project.
/// </summary>
public static class GlobalVar
{
/// <summary>
/// Global variable that is constant.
/// </summary>
public const string GlobalString = "Important Text";
/// <summary>
/// Static value protected by access routine.
/// </summary>
static int _globalValue;
/// <summary>
/// Access routine for global variable.
/// </summary>
public static int GlobalValue
{
get
{
return _globalValue;
}
set
{
_globalValue = value;
}
}
/// <summary>
/// Global static field.
/// </summary>
public static bool GlobalBoolean;
}
You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.
Just declare the variable at the starting of a class.
e.g. for string variable:
public partial class Login : System.Web.UI.Page
{
public string sError;
protected void Page_Load(object sender, EventArgs e)
{
//Page Load Code
}
You can create a variable with an application scope
Source: Stackoverflow.com