Defining Constants


A constant looks like a variable, but the value behind the constant can't be changed. You assign a value to a constant that the compiler can resolve at compile time before executing your program. You can't set a constant equal to a function, because the result of the function would only be known when you execute the program. Constants can only be declared inside a class or inside a function. If declared inside a function, the constant can only be used inside that function. If declared in a class the constant can be used from anywhere (if marked as public).

To define a constant:

  1. Type the word const followed by a space.

  2. Enter the type of constant, which must be primitive: int, double, string, etc.

  3. Set the constant equal to a literal value, or to a simple calculation that involves literal values (10 + 20, for example).

  4. End the expression with a semicolon ( Figure 2.19 ).

    Figure 2.19 Constants are variables that are read-only. They are handy in making the intent of your code more obvious. For example, x = 3.14 isn't as clear as x = pi.
     const double PI = 3.14; PI = 3.1; //this line is illegal 

graphics/tick.gif Tips

  • Although constants normally hold numeric values, they can also hold string values ( Figure 2.20 ).

    Figure 2.20 Constants can store strings as well.
     const string CLOSED_STATUS = "closed"; const string OPEN_STATUS = "open"; 
  • Once you declare a constant, you can use the constant throughout your code ( Figure 2.21 ).

    Figure 2.21 Using constants can also make your code easier to maintain. For example, if you were to use the constant Open_Status throughout your program, if at some point the constant value changes, it only needs to be changed in one place. If you used the literal value, you would have to change every line in which the value was used.
     const string ClosedStatus = "closed"; const string OpenStatus = "open";  string toDoStatus = OpenStatus;  
  • Constant values can't be changed at run time.

  • Constants are usually named using what is called PascalCasing. In PascalCasing the first letter of each word is capitalized. Here's an example: FakePhone="555-1212."

  • Constants can only be declared inside of a class or inside a function (which I will define later in this chapter) ( Figure 2.22 ).

    Figure 2.22 You refer to the constant by using the class name plus the constant name , in this case Math.pi.
     class Math {  //inside of class definition  public const double PI = 3.14; } class Checking {    void OrderChecks(byte amount)    {  //inside of function  const byte MinChecks = 20;       const byte MaxChecks = 250;       if (amount >= MinChecks &&           amount <= MaxChecks)       {          //do something here       }    } } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net