Reputation: 14694
Is it possbile to make a variable global in C#?
Upvotes: 4
Views: 3867
Reputation: 61497
Not directly, you could either use a static class with a static property (strongly not recommended) or employ a mean to create a singleton (not recommended). The better way would be to use some sort of dependecy injection to supply the values (recommended).
Upvotes: 0
Reputation: 33071
You can make a public class with a public static variable...but it really isn't a good programming practice to do it.
Upvotes: 0
Reputation: 562
Not really. You can make a new class, call it anything you want, make it static, and have a static public property/variable on that.
Why do you want to do this? Is this a constant?
You can also use (if it is a constant value) the appsettings node in your web/app config file.
Upvotes: 0
Reputation: 133122
No, It is not. The analogue/workaround is a public static variable of some class. HTH
Upvotes: 0
Reputation: 61497
Not directly, you could either use a static class with a static property (not recommonded) or employ a mean to create a singleton. The better way would be to use some sort of dependecy injection to supply the values.
Upvotes: 2
Reputation: 1503869
Well, you can make a public static variable:
public static class Globals
{
public static string Foo;
}
However, I'd strongly urge you not to do this:
I'd urge you to try very hard to design away from globals. If you could tell us more about why you think you want a global variable, we may be able to give you some advice on how to avoid it in this particular case :)
Upvotes: 10