First, the static keyword in the C# language describes a member such as a
field, property or method that is part of a type, not an instance of
the type. The static keyword was mainly chosen for historical reasons as
it was used in C and C++. The program here contains two files: first a
file that contains the global variables in a public static class, and
then the Program.cs file that uses the global class.
// 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;
}
~~~ Program that uses global variables (Program.cs, C#) ~~~
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 two previous values.
Console.WriteLine(GlobalVar.GlobalValue);
Console.WriteLine(GlobalVar.GlobalBoolean);
}
}
//out put
Important Text
400
True