Moving from C++ to C#, I discovered that constants in the way I was using them are not supported; however, they can be emulated. they are now defined in their own class as static variables; I go a step further by making them private and only available through a property.
Before I show a code example, let's explore static further. When a variable is declared as static, the variable is essentially global. All instances of the class share the same static variable. A static variable is initialized to zero unless an explicit initializer is specified.
FIrst, let's look at the class that defines the constants:
namespace Globals
{
public class clsGlobalDefs
{
private static string _c1 = "Constant 1";
private static string _c2= "This is a constant string";
public string c1
{
get { return _c1; }
}
public string c2
{
get { return _c2; }
}
public clsGlobalDefs()
{
}
}
A few notes on the above class:
- I like placing the constants in their own namespace and their own DLL. This allows me to use the same constants across multiple projects.
- Note the use of the static qualifier
- Note the use of properties
To use class clsGlobalDefs:
- Reference clsGlobalDefs through a using statement : using Globals
- Instantiate clsGlobalDefs: clsGlobalDefs GlobalDefs = new clsGlobalDefs();
- Access the constant through the class' property:
String s;
s = GlobalDefs.c1;
-or-
s = "This is constant #1: " + GlobalDefs.c1