0

Ok, so I'm reading a bit on Global variables and everyone's thought is that they are just evil and bad and are not to be used which confuses me.

I have an app I'm developing where one Screen 1, a user makes a choice from a menu and later on, on another screen, the results of that choice are displayed. To me, that constitutes a global variable so that the last screen is able to read the value and display it.

Now I read something about using Auctions instead. I have to read up on those but I might as well ask, can I manipulate the variables across different forms? If so, wouldn't that be the same as a global variable?

Are there any other best practices for this sort of thing?

Confused

  • Try to keep information as close to the code that needs it. – TaW Oct 25 '18 at 21:03
  • 1
    Your example only constitutes sharing information across Screens. Depending on wich display technology you use (WinForms, WPF/UWP, Console), this can be anywhere from Trivial to "enticing you do go for global variables". – Christopher Oct 25 '18 at 21:03
  • 1
    See this [post](https://stackoverflow.com/questions/14368129/c-sharp-global-variables) – Marty1452 Oct 25 '18 at 21:03
  • Possible duplicate of [Are global variables bad?](https://stackoverflow.com/questions/484635/are-global-variables-bad) – user3486184 Oct 25 '18 at 21:58
  • A "screen" should be a class, like it is in Winforms (Form) or WPF (Window). The choice should thus be a class member variable, not a global variable. With perhaps a public property that exposes it, albeit that nobody should care too much what was chosen. The "last screen" ought to not care how the menu system decided to activate it. Encapsulation is one of the pillars of object-oriented programming. – Hans Passant Oct 26 '18 at 01:13

1 Answers1

0

I think it has been said here other times, but with Global variables its hard to keep track what methods or areas of the project code modify those variables so it can lead to less overall clarity and troubleshooting issues.

In programming there are the concepts of encapsulation and low coupling that you might know about. Global variables practically are at the opposite end of encapsulation and low coupling. Encapsulation refers to containing everything in one "unit" and low coupling to the low interdependence of these units with the purpose of them being easily reused and maintained.

Sometimes though the benefit of using a global variable can outweigh the downsides. In general its good to avoid using global variables in favor of functions that exchange output among them for clarity but other times using a global variable is justifiable.

Razvan Emil
  • 533
  • 9
  • 25
  • Ok, so what about auctions? Would they be considered global variables or are they common place? Would they be the preferred method in C#? They seem nice to code but if there is a more practical method, I'd like to know. Thank you – stackoverflow_user Oct 25 '18 at 21:17