2

I'm currently learning C# having been most familiar with Ruby previously, and I was writing some code which required a bool variable to be accessed from multiple places, to check and/or set the state. In Ruby this would be a piece of cake, just declare $my_global_variable = false (or whatever). Having looked this up I was successfully able to replicate this in C# by declaring the following:

public class GlobalVariables  
{  
    public static bool exampleGlobalVariable;  
}  

And then accessing GlobalVariables.exampleGlobalVariable whenever I need to. However everything I read about global variables in C# suggests that they're considered problematic and if you implement them you're a terrible person.

So my question is, what alternatives are there? Passing variables back and forth is messy to my eye and sometimes it's not even possible - if a method is already passing back a variable, for example.

Is there another way of achieving this functionality that's neat and idiomatic for C#?

user2789658
  • 49
  • 1
  • 4
  • Related: http://stackoverflow.com/questions/895595/how-do-i-persist-data-without-global-variables In general you should not use global variables (which you could have with `public static` variables) because you can run into threading issues or race conditions if multiple threads access this variable in the same time. It seems to be simpler but actually it's a source for nasty (future) problems. – Tim Schmelter Jun 07 '16 at 09:47
  • I wonder which answer you want to hear. `public static` variables are accessible from anywhere, for non-static variables you simply need an instance. Have a look how `Settings` class works (you have to specify name and cast result, because it's not strong type dictionary) or binding in xaml (using reflection). What is your case? – Sinatr Jun 07 '16 at 09:48

0 Answers0