Global variable in console applications
give me an example for global variable in console applications?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Iftikar HussainRank #423 · 5.9K reputationPosted Jul 14, 2013, 12:36 AM EDT
Here it is
Since by default for every console application Main() method is entry point and it is a static. In static method you can use only static variable only
Regards,
Iftikar
VulpesRank #55 · 29.2K reputationPosted Jul 14, 2013, 12:49 AM EDT
If you're going to do that, then you might as well make them static so that there's only the one copy anyway.
VulpesRank #55 · 29.2K reputationPosted Jul 14, 2013, 12:02 AM EDT
All variables must be defined within a class or struct.
However, one way to simulate a global variable is to add an internal static field to the class which contains your Main() method. For example:
class Program
{
internal static int GlobalInt = 42;
static void Main()
{
// blah
}
}
You can now access the global variable from any other class in the application using the expression Program.GlobalInt.
Sreekanth ReddyRank #726 · 3.2K reputationPosted Jul 14, 2013, 12:22 AM EDT