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.
Aaronaught
source share