How do I declare a variable so that every class (*.cs) can access its content, without an instance reference?
5 Answers
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 specificnamespace
(so that it will be placed in the global application namespace); - insert the proper using directive for retrieving the variables from another
namespace
.

- 23,232
- 8
- 74
- 98
-
@Zarathos does the class have to be static as well ? – kosnkov Jun 10 '15 at 06:51
-
5Well it's not necessary but I don't see why you should instantiate it. – Tommaso Belluzzo Jun 13 '15 at 00:40
-
If you have to instantiate its per definition not "global" anymore, not part of the application state – Viking Jan 15 '19 at 07:21
-
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. – Tomer Cahal Feb 02 '20 at 17:54
-
2Without 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. – Tommaso Belluzzo Feb 02 '20 at 18:01
You can have static members if you want:
public static class MyStaticValues
{
public static bool MyStaticBool {get;set;}
}

- 43,562
- 11
- 100
- 154
-
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. – cregox Nov 15 '13 at 16:45
-
3@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. – Federico Berasategui Nov 15 '13 at 16:48
-
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. – cregox Nov 15 '13 at 16:54
-
@cawas a `static property or field` must be `inside a class`. It can never be declared as a standalone thing floating in limbo. That's the difference between `static members` in C# and `"global variables"` in other languages. – Federico Berasategui Nov 15 '13 at 16:57
-
1I feel like you're either evading my question or I'm not clear. But I got it answered already. Here: http://stackoverflow.com/a/20010543/274502 – cregox Nov 15 '13 at 21:05
-
9I now realize what I meant is that *static members are conceptually and practically **global vars*** (except maybe for that [heap thing](http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap), which only makes difference *[unless you are writing unsafe code or doing some sort of heavy interoperating with unmanaged code](http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx)*). So I don't know why would anyone say "*there's no such thing as global variable in csharp*". It confused me a lot. – cregox Nov 16 '13 at 09:32
-
The difference is in how "global" is "a global". In C# it always belongs to some class, while in other languages it is... well, _floating in limbo_ (or window, or process...) – Lukasz Matysiak Sep 23 '19 at 07:48
-
I see what you're saying about properties not being global. They're still associated with a class in C# when using a static class, but they're accessible globally. You can set a static property in class A then use the value in class B, C, D, etc. – Rich Oct 22 '19 at 05:31
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,
- Wrap all such Global variables into a single
static
class (for manageability). - 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;

- 13,110
- 9
- 77
- 127
-
2`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#" – ICW Nov 05 '22 at 20:09
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);

- 2,513
- 1
- 21
- 27
-
Thank you! this little trick is saving me hours in a VBA to C# conversion. – Eric Oct 26 '20 at 17:26
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);

- 2,832
- 2
- 23
- 31