How to define global variables in c#?

In C#, the static keyword can be used to define global variables. Global variables should be defined outside the class and can be accessed throughout the program. Here is an example:

public class MyClass
{
    public static int globalVariable = 10;
}

public class Program
{
    static void Main(string[] args)
    {
        // 访问全局变量
        Console.WriteLine(MyClass.globalVariable);
        
        // 修改全局变量的值
        MyClass.globalVariable = 20;
        
        // 再次访问全局变量
        Console.WriteLine(MyClass.globalVariable);
    }
}

In the above example, globalVariable is defined as a static variable, which can be accessed in any method within the MyClass class. In the Main method, we can directly access and modify its value using MyClass.globalVariable. The output will be:

10
20

This indicates that the value of the global variable has been successfully changed.

bannerAds