Global variable in static method

It seems basic, but I find it pretty trivial. Just how would you recommend setting a global variable with a static class (i.e. Console Application)?

To give you a little more information, the main method is to call some custom event handlers, which I hope to get / set variables.

Any ideas or suggestions that you have are appreciated.

+6
c # static console-application
source share
3 answers

The easiest way -

public static Object MyGlobalVariable; 

which creates a public static field. A little better:

 public static Object MyGlobalVariable { get; set; } 

What creates a public static property.

+9
source share

There are no global variables in C #. The variable is always local. The basic unit of code is a class, and inside the class you have fields, methods, and properties.

You can imitate a "global variable" by creating a public static field or property in some class, but it should not. C # makes this difficult for a very good reason; global variables are pure evil. They violate several good OO design principles β€” encapsulation, loose coupling, and a high degree of traction β€” to name a few.

I understand that this is a beginner, but I think, because it is a question for beginners, it is so important to talk about it. Now is the best time to start exploring which tactics are actively discouraged or even dangerous in C #, and using a static field / property as a global variable is about six of them. There is legal use for these designs, but transferring data from place to place is not one of them.

If two different classes depend on the same information, pass the information from the source to the destination. This is usually done either through the constructor, or as an argument to the called method. You should always have one and only one instance that truly "owns" this information; β€œglobal” information means that you cannot talk about who or what may depend on it at any given time.

Please think about this and try to think of other ways of exchanging the information you want to store in a global variable (i.e. by providing it as an argument to a constructor or method). If you are not sure, send an example of what you are trying to do, and we will help.

+13
source share

Not 100% sure, but you can try singleton to hold variables. Not knowing that you are trying to do this, it is difficult to recommend if this solution does not bite you along the way.

http://www.yoda.arachsys.com/csharp/singleton.html

+1
source share

All Articles