C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: We see 2 files: one that contains the global variables in a static class, and Program.cs, which uses the global class.
Const: GlobalString is a public global variable. You must assign its value inline with its declaration at the class declaration space.
Property: GlobalValue is a public static property with get and set accessors. This is an access routine of a backing store.
Field: A global field could cause problems in your program because it does not use an access routine.
Global variables class, GlobalVar.cs: C#
/// <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;
}
C# program that uses global variables, Program.cs
using System;
class Program
{
static void Main()
{
// Write global constant string.
Console.WriteLine(GlobalVar.GlobalString);
// Set global integer.
GlobalVar.GlobalValue = 400;
// Set global boolean.
GlobalVar.GlobalBoolean = true;
// Write the 2 previous values.
Console.WriteLine(GlobalVar.GlobalValue);
Console.WriteLine(GlobalVar.GlobalBoolean);
}
}
Output
Important Text
400
True
Tip: These methods provide another layer of abstraction over how you use the global variables.
And: In the example, the property accessor (get) is an accessor routine. Please see Code Complete by Steve McConnell, page 340.
Also: This is a problem in many Windows Forms applications that use BackgroundWorker threads.
BackgroundWorker