How do I declare a variable so that every class (*.cs) can access its content, without an instance reference?
In C#
you cannot define true global variables (in the sense that they don't belong to any class).
This being said, the simplest approach that I know to mimic this feature consists in using a static class
, as follows:
public static class Globals
{
public const Int32 BUFFER_SIZE = 512; // Unmodifiable
public static String FILE_NAME = "Output.txt"; // Modifiable
public static readonly String CODE_PREFIX = "US-"; // Unmodifiable
}
You can then retrieve the defined values anywhere in your code (provided it's part of the same namespace
):
String code = Globals.CODE_PREFIX + value.ToString();
In order to deal with different namespaces, you can either:
Globals
class without including it into a specific namespace
(so that it will be placed in the global application namespace);namespace
.