Global variables are variables that is accessed in the entire scope as you say, usually this is done with static
classes. Example code:
public class Demo {
public static string ThisIsGlobal = "Global";
private string _field = "this is a field in the class";
public void DoSomething()
{
string localVariable = "Local";
string localVariable2 = ThisIsGlobal; // VALID
}
public static void GlobalMethod()
{
string localVariable = _field; // THIS IS NOT VALID!
}
}
Many people say that global variables and state are bad, I don't think so as long as you use it as it should be used. In the above example the ThisIsGlobal
is a global variable because it have the static
keyword. As you see in the example you can access static variables from instance methods, but not instance variables from static methods.