Posts
7
Comments
2
Trackbacks
0
C# Constants & Global Variables
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:

  1. I like placing the constants in their own namespace and their own DLL.  This allows me to use the same constants across multiple projects.
  2. Note the use of the static qualifier
  3. Note the use of properties
To use class clsGlobalDefs:

  1. Reference clsGlobalDefs through a using statement : using Globals
  2. Instantiate clsGlobalDefs: clsGlobalDefs GlobalDefs = new clsGlobalDefs();
  3. Access the constant through the class' property:
String s;
s = GlobalDefs.c1;

-or-

s = "This is constant #1: " + GlobalDefs.c1


posted on Friday, July 03, 2009 8:16 AM Print
Comments
No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *  
 
News