OneBite.Dev - Coding blog in a bite size

Declare A Global Variable In C#

Code snippet for how to Declare A Global Variable In C# with sample and detail explanation

In C#, creating a global variable can streamline your code, reduce redundancy, and ultimately lead to a better, more effective product. While it has to be used carefully because it can introduce potential bugs and make code harder to debug, it can be a helpful tool in your programming repertoire.

Code Snippet For Declaring A Global Variable In C#

class Program
{
    public static int myGlobalInt = 25; //Here we declare a global variable

    static void Main(string[] args)
    {
        Console.WriteLine(myGlobalInt); //We can now use the global variable within this method 
    }
}

Code Explanation for Declaring A Global Variable In C#

In this code snippet, a global variable named myGlobalInt is declared within the Program class but outside any function or method. This variable has a public access modifier and static keyword.

  1. Public Access Modifier: Using ‘public’ as an access modifier means the variable can be accessed from any part of the program. We could have also used ‘internal’ if we wanted the variable to be available only within the same assembly, but for our global variable example, ‘public’ is necessary.

  2. Static Keyword: ‘Static’ keyword is used because we want this variable to be created and initialized only once and its value kept throughout the whole runtime of the program. Only a single copy of the variable exists and changes to its value from any location in the program are seen in all locations.

The variable myGlobalInt can be used throughout all the methods of class Program, so it is global for this class. The value of myGlobalInt will be the same for all methods in this class.

In Main method, we access called myGlobalInt without needing to create an instance of the class. It’s worth noting that you cannot have truly global variables in C# like you can in languages like C or C++. In C#, you can only declare class-level or static variables.

Remember that though global variables may seem convenient, it is wise to use them sparingly. Over-reliance on global variables can make your code difficult to debug and understand, and could lead to unexpected results.

c-sharp