150

How do I declare a variable so that every class (*.cs) can access its content, without an instance reference?

0

5 Answers 5

192

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

This being said, the simplest approach that I know to mimic this feature consists in using 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 } 

You can then retrieve the defined values anywhere in your code (provided it's part of the same namespace):

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

In order to deal with different namespaces, you can either:

  • declare the Globals class without including it into a specific namespace (so that it will be placed in the global application namespace);
  • insert the proper using directive for retrieving the variables from another namespace.
Sign up to request clarification or add additional context in comments.

5 Comments

@Zarathos does the class have to be static as well ?
Well it's not necessary but I don't see why you should instantiate it.
If you have to instantiate its per definition not "global" anymore, not part of the application state
Hi, what would be the difference if I would not type the static keyword in the class? I only made the string FILE_NAME static, I tried and it still worked for me.
Without the static attribute your class will be instantiable (Globals g = new Globals()). It doesn't alter the behavior of static variables declared inside, but it doesn't look really useful.
85

You can have static members if you want:

public static class MyStaticValues { public static bool MyStaticBool {get;set;} } 

8 Comments

While I do agree, could you please expand on why there is no such thing as a global variable in C#? I was trying to think of a good reason why that very static example you provided can't really be considered a global var.
@cawas because the very concept of a "global variable" (hanging from nowhere, floating in limbo, not belonging to any class) goes against the very nature of OOP. and C# is strictly object oriented.
Yes, that's all the concept I agree with. But by making that static member you just created a kind of global var. How that differs from the global var you said doesn't exist? I'd like to see a practical example.
I feel like you're either evading my question or I'm not clear. But I got it answered already. Here: stackoverflow.com/a/20010543/274502
I now realize what I meant is that static members are conceptually and practically global vars (except maybe for that heap thing, which only makes difference unless you are writing unsafe code or doing some sort of heavy interoperating with unmanaged code). So I don't know why would anyone say "there's no such thing as global variable in csharp". It confused me a lot.
|
28

First examine if you really need a global variable instead using it blatantly without consideration to your software architecture.

Let's assuming it passes the test. Depending on usage, Globals can be hard to debug with race conditions and many other "bad things", it's best to approach them from an angle where you're prepared to handle such bad things. So,

  1. Wrap all such Global variables into a single static class (for manageability).
  2. Have Properties instead of fields(='variables'). This way you have some mechanisms to address any issues with concurrent writes to Globals in the future.

The basic outline for such a class would 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. } 

Usage from other classes (within same namespace)

// Read bool areWeAlive = Globals.Expired; // Write // past deadline Globals.Expired = true; 

1 Comment

First examine if you really need a global variable instead using it blatantly without consideration to your software architecture. - The question didn't asked "should I use global variables in C#", it asked "How do I create a global variable in C#"
12

A useful feature for this is using static

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

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

But you can import it like this in order to no longer write the class name in front of its static properties:

using static Globals; [...] Console.WriteLine("Pi is " + PI); 

1 Comment

Thank you! this little trick is saving me hours in a VBA to C# conversion.
4

Zotta's answer is good. You can also set up global variables with your ".csproj" project file. This way, your code doesn't even need a using statement.

Specify your global variables in a static class:

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

In your ".csproj" file, add this item group:

<ItemGroup> <Using Include="Globals" Static="true" /> </ItemGroup> 

Now you can use global variables in your code without any further ceremony:

Console.WriteLine("Pi is " + PI); 

1 Comment

<ItemGroup> <Using Include="MyProject.Globals"> <Static>True</Static> </Using> </ItemGroup>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.