[c#] How to use Global Variables in C#?

How do I declare a variable so that every class (*.cs) can access its content, without an instance reference?

This question is related to c# variables scope

The answer is


In C# you cannot define true global variables (in the sense that they don't belong to any class).

This being said, the simplest approach that I know to mimic this feature consists in using a static class, as follows:

public static class Globals
{
    public const Int32 BUFFER_SIZE = 512; // Unmodifiable
    public static String FILE_NAME = "Output.txt"; // Modifiable
    public static readonly String CODE_PREFIX = "US-"; // Unmodifiable
}

You can then retrieve the defined values anywhere in your code (provided it's part of the same namespace):

String code = Globals.CODE_PREFIX + value.ToString();

In order to deal with different namespaces, you can either:

  • declare the Globals class without including it into a specific namespace (so that it will be placed in the global application namespace);
  • insert the proper using directive for retrieving the variables from another namespace.

A useful feature for this is using static

As others have said, you have to create a class for your globals:

public static class Globals {
    public const float PI = 3.14;
}

But you can import it like this in order to no longer write the class name in front of its static properties:

using static Globals;
[...]
Console.WriteLine("Pi is " + PI);

There's no such thing as a global variable in C#. Period.

You can have static members if you want:

public static class MyStaticValues
{
   public static bool MyStaticBool {get;set;}
}

First examine if you really need a global variable instead using it blatantly without consideration to your software architecture.

Let's assuming it passes the test. Depending on usage, Globals can be hard to debug with race conditions and many other "bad things", it's best to approach them from an angle where you're prepared to handle such bad things. So,

  1. Wrap all such Global variables into a single static class (for manageability).
  2. Have Properties instead of fields(='variables'). This way you have some mechanisms to address any issues with concurrent writes to Globals in the future.

The basic outline for such a class would be:

public class Globals
{
    private static bool _expired;
    public static bool Expired 
    {
        get
        {
            // Reads are usually simple
            return _expired;
        }
        set
        {
            // You can add logic here for race conditions,
            // or other measurements
            _expired = value;
        }
    }
    // Perhaps extend this to have Read-Modify-Write static methods
    // for data integrity during concurrency? Situational.
}

Usage from other classes (within same namespace)

// Read
bool areWeAlive = Globals.Expired;

// Write
// past deadline
Globals.Expired = true;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to scope

Angular 2 - Using 'this' inside setTimeout Why Is `Export Default Const` invalid? How do I access previous promise results in a .then() chain? Problems with local variable scope. How to solve it? Why is it OK to return a 'vector' from a function? Uncaught TypeError: Cannot read property 'length' of undefined Setting dynamic scope variables in AngularJs - scope.<some_string> How to remove elements/nodes from angular.js array Limiting number of displayed results when using ngRepeat A variable modified inside a while loop is not remembered