受欢迎的博客标签

C# Global Variables

Published

How to define a static class to make "globals" accessible from anywhere

A global variable is a variable accessible anywhere, for example a field "counter" type integer.
The global variable can be accessed from any function or class within the namespace.

C# is an object-oriented programming (OOP) language and does not support global variables directly. The solution is to add a static class containing the global variables. Using a global variable violates the OOP concept a bit, but can be very useful in certain circumstances.

Use a global variable, implemented as public static property. Store globals in a static class.

define a   Global Variables (static class):

sample1:

static class Globals
{
    // global int
    public static int counter;

    // global function
    public static string HelloWorld()
    {
        return "Hello World";
    }

    // global int using get/set
    static int _getsetcounter;
    public static int getsetcounter
    {
        set { _getsetcounter = value; }
        get { return _getsetcounter; }
    }
}

Please note, that you need to add the static keyword before class and type!

The "static" keyword means the variable is part of the type and not an instance of the type!

 

The class "Globals" can be used anywhere without using an instance:

Globals.counter = 10;
int localcounter = Globals.counter;
string somestring = Globals.HelloWorld();
Globals.counter2 = 30;
int localcounter2 = Globals.counter2;

 

Be aware, that using global variables is not the answer to all questions and should only be used if using instances/parameters is not practical!

You should also be careful when using multithreading, e.g. a background task. Make sure, that only one thread has access to the global (static) variable at a time - or add some kind of lock routine - to avoid conflicts.

 

sample2:

using System.Collections.Generic;
using SimplCommerce.Infrastructure.Localization;
using SimplCommerce.Infrastructure.Modules;

namespace SimplCommerce.Infrastructure
{
    public static class GlobalConfiguration
    {
        public static IList<ModuleInfo> Modules { get; set; } = new List<ModuleInfo>();

        public static IList<Culture> Cultures { get; set; } = new List<Culture>();

        public static string DefaultCulture => "en-US";

        public static string WebRootPath { get; set; }

        public static string ContentRootPath { get; set; }

        public static IList<string> AngularModules { get; } = new List<string>();

        public static void RegisterAngularModule(string angularModuleName)
        {
            AngularModules.Add(angularModuleName);
        }
    }
}

What is the difference between a "Global Variables" and a "Local Variables"?

int global_c; // can be used by any other file with 'extern int global_c;'

static int static_c; // cannot be seen or used outside of this file.

int foo(...)
{
   int local_c; // cannot be seen or used outside of this function.
}