Global? What is it? There is no such concept in .NET; I think this is because this concept is evil, so it was eliminated from the architecture. You never really need "global" variables, but static variables of class or structure can be made visible to whole application domain. If the access modifier of such variable is
internal
, it is visible to the part of application domain limited by the same assembly; if the access modifier is
public
, the variable is accessible in whole application domain from any assembly.
This is equivalent to the globally-accessed variable. However, this kind of programming
should be best avoided.
If you need global access to some object unique to application domain, you can use
singleton (
http://en.wikipedia.org/wiki/Singleton_pattern[
^])
design pattern (
http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29[
^]).
Here is how:
public class MySingleton {
private MySingleten() {}
public int value;
public string value;
public MySingleton Instance {
get {
if (fInstance == null)
fInstance = new MySingleton();
return fInstance;
}
}
private static fInstance;
}
Pay attention that the
Lazy evaluation pattern (
http://en.wikipedia.org/wiki/Lazy_evaluation[
^]) is also used.
In many cases the singleton needs to be shared between different threads. In this case, locking can be conveniently implemented inside singleton class in a way transparent to the users of the singleton.
See more detailed article with good non-thread-safe and thread-safe implementations of the Singleton:
http://csharpindepth.com/Articles/General/Singleton.aspx[
^].
—SA