As other people mentioned before either use App.Current.Properties
or create a static class.
I am here to provide an example for those who need more guidance with the static class.
- Add a new Class
Right-click your project name in your solution explorer Add > New Item
choose Class
give it a name (I usually name it GLOBALS)
- What that cs file should look like
using System;
namespace ProjectName
{
public static class GLOBALS
{
public static string Variable1 { get; set; }
public static int Variable2 { get; set; }
public static MyObject Variable3 { get; set; }
}
}
- Add references into .cs files where you intend to use those variables
using ProjectName
- We're done. Use it. Examples:
GLOBALS.Variable1 = "MyName"
Console.Write(GLOBALS.Variable1)
GLOBALS.Variable2 = 100;
GLOBALS.Variable2 += 20;
GLOBALS.Variable3 = new MyObject();
GLOBALS.Variable3.MyFunction();
A note about unit testing and static classes / static variables
It is generally considered bad practice to use a static class to hold global variables, one of the major reasons being that it can significantly hinder the ability to properly unit test your code.
If however you need code that is testable and you do still want to use a static global variable class, then at least consider using a singleton pattern for accessing your GLOBALS. [more details here: https://jonskeet.uk/csharp/singleton.html]
Below is a useful snippet of what I mean. Make GLOBALS abstract and remove the static, then add the following inside GLOBALS class:
private static GLOBALS instance = null;
/// <summary>
/// The configuration instance used by the application and unit tests
/// </summary>
public static GLOBALS Instance
{
get
{
if (instance == null)
{
//Create the default configuration provider
instance = new AppConfigConfiguration();
}
return instance;
}
set
{
instance = value;
}
}
AppConfigConfiguration (in the example above) is an application specific settings class which derives from GLOBALS. The singleton pattern allows other configurations to also be derived, and optionally set on the Instance property, a common occurrence being prior to unit tests running so that test specific settings can be assured.