How to use global variables in c #?

How can I declare a variable so that each class (* .cs) can access its contents without reference to the instance?

+84
variables scope c #
Jan 16 '13 at 21:26
source share
4 answers

In C# you cannot define true global variables (in the sense that they do not belong to any class).

With this, the simplest approach that I know to imitate this function is to use a static class as follows:

 public static class Globals { public const Int32 BUFFER_SIZE = 512; // Unmodifiable public static String FILE_NAME = "Output.txt"; // Modifiable public static readonly String CODE_PREFIX = "US-"; // Unmodifiable } 

Then you can get certain values ​​anywhere in your code (provided that it is part of the same namespace ):

 String code = Globals.CODE_PREFIX + value.ToString(); 

To deal with different namespaces, you can:

  • declare the Globals class without including it in a specific namespace (so that it is placed in the namespace of global applications);
  • insert the correct directive to extract the variables from another namespace .
+97
Jan 16 '13 at
source share

There is no such thing as a global variable in C #. Period.

If you want, you can have static elements:

 public static class MyStaticValues { public static bool MyStaticBool {get;set;} } 
+67
Jan 16 '13 at 21:28
source share

First, check to see if you need a global variable that uses it blatantly instead, ignoring your software architecture.

Suppose he passes the test. Depending on the usage, Globals can be difficult to debug with race conditions and many other “bad things”, it is better to approach them from an angle where you are ready to deal with such bad things. So,

  • Wrap all such global variables in one static class (for manageability).
  • Have properties instead of fields (= 'variables'). Thus, you have some mechanisms to solve any problems while writing to Globals in the future.

The main plan for this class will be:

 public class Globals { private static bool _expired; public static bool Expired { get { // Reads are usually simple return _expired; } set { // You can add logic here for race conditions, // or other measurements _expired = value; } } // Perhaps extend this to have Read-Modify-Write static methods // for data integrity during concurrency? Situational. } 

Using other classes (inside the same namespace)

 // Read bool areWeAlive = Globals.Expired; // Write // past deadline Globals.Expired = true; 
+21
Oct 31 '13 at 16:19
source share

A useful feature for this is using static

As others have said, you must create a class for your globals:

 public static class Globals { public const float PI = 3.14; } 

But you can import it so that you no longer write the class name in front of its static properties:

 using static Globals; [...] Console.WriteLine("Pi is " + PI); 
0
Jun 12 '19 at 19:50
source share



All Articles