Team LiB
Previous Section Next Section

Constant and Static Values

A constant is a value that cannot be modified after it is assigned. Constants can be divided into two broad categories:

These variables are typically given identifiers that are in all uppercase letters to help signify that they are read-only. You should use the const statement in cases where you would use the #define statement in C++.

The static keyword tells the compiler that the value of the variable will never be destroyed and a single instance is always stored. These variables are initialized to zero by default.

The following examples demonstrate using constant and static values.

Code Example: Constants
Start example

using System;

namespace MyNamespace
{
          class MyMainClass
          {
                static void Main(string[] args)
                {
                      //const tells the compiler that the value can't be modified
                      //after it is assigned
                      const int MyInt = 0;
                      //This is invalid and would be caught by the compiler
                      MyInt = 5;
                }
          }
}
End example
Code Example: Static
Start example
using System;
namespace MyNamespace
{
         class MyMainClass
         {
               //There will always be one value for this member variable
               public static int MyClassInt;
               static void Main(string[] args)
               {
               }

               MyMainClass()
               {
                     MyClassInt++;
               }
         }
}
End example

Team LiB
Previous Section Next Section