gurehbgui
gurehbgui

Reputation: 14694

Possible to make a global Var. C#

Is it possbile to make a variable global in C#?

Upvotes: 4

Views: 3867

Answers (6)

Femaref
Femaref

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

Dismissile
Dismissile

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

Matt
Matt

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

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133122

No, It is not. The analogue/workaround is a public static variable of some class. HTH

Upvotes: 0

Femaref
Femaref

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

Jon Skeet
Jon Skeet

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:

  • It becomes unclear what's using the variable
  • There's no sort of thread safety
  • It makes testing a pain (in particular if you want to parallelize tests)

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

Related Questions