Constants

Variables are a powerful tool, but sometimes you want to use a defined value, one whose value you want to ensure remains constant. A constant is like a variable in that it can store a value. However, unlike a variable, you cannot change the value of a constant while the program runs.

For example, you might need to work with the Fahrenheit freezing and boiling points of water in a program simulating a chemistry experiment. Your program will be clearer if you name the variables that store these values FreezingPoint and BoilingPoint, but you do not want to permit their values to be changed while the program is executing. The solution is to use a constant. Constants come in three flavors: literals, symbolic constants, and enumerations.

Literal Constants

A literal constant is just a value. For example, 32 is a literal constant. It does not have a name; it is just a literal value. And you can’t make the value 32 represent any other value. The value of 32 is always 32. You can’t assign a new value to 32, and you can’t make 32 represent the value 99 no matter how hard you might try. You’ll use literal constants a lot, but you probably won’t think of them as such.

Symbolic Constants

Symbolic constants assign a name to a constant value. You declare a symbolic constant using the following syntax:

const type identifier =value;

The const keyword is followed by a type, an identifier, the assignment operator (=), and the value to assign to the constant.

This is similar to declaring a variable except that you start with the keyword const and symbolic constants must be initialized. Once initialized, a symbolic constant cannot be altered. For example, in the following declaration, 32 is a literal constant and FreezingPoint is a symbolic constant of type int:

const int FreezingPoint = 32;

Example 3-4 illustrates the use of symbolic constants.

Example 3-4. This program defines two symbolic constants and outputs their values; it won’t compile, though, because of the attempt to assign a new value to a constant

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example_3_4_ _ _ _Symbolic_Constants
{
    class Values
    {
        static void Main( )
        {
            const int FreezingPoint = 32; // degrees Fahrenheit
            const int BoilingPoint = 212;

            System.Console.WriteLine("Freezing point of water: {0}", 
                                      FreezingPoint);
            System.Console.WriteLine("Boiling point of water: {0}", 
                                      BoilingPoint);

            BoilingPoint = 21;
        }
    }
}

Example 3-4 creates two symbolic integer constants: FreezingPoint and BoilingPoint. (See the “Naming Conventions” sidebar for a discussion of how to name symbolic constants.)

These constants serve the same purpose as using the literal values 32 and 212 for the freezing and boiling points of water, respectively, in expressions that require them. However, because the constants have names, they convey far more meaning. It might seem easier to just use the literal values 32 and 212 instead of going to the trouble of declaring the constants, but if you decide to switch this program to Celsius, you can reinitialize these constants at compile time to 0 and 100, respectively, and all the rest of the code should continue to work.

If you try to run the program shown in Example 3-4, you’ll receive the following error:

The left-hand side of an assignment must be a variable, property or indexer

That’s because the assignment in this line is illegal:

BoilingPoint = 21;

You can’t assign a new value to a constant, so the compiler complains. To fix this problem, simply comment out the offending line by adding two slashes in front of it, like this:

// BoilingPoint = 21;

Now the program runs as expected, without an error.

Enumerations

Enumerations provide a powerful alternative to literal or simple symbolic constants. An enumeration is a distinct value type, consisting of a set of named constants (called the enumerator list).

In Example 3-4, you created two related constants:

const int FreezingPoint = 32;
const int BoilingPoint = 212;

You might want to add a number of other useful constants to this list as well, such as:

const int LightJacketWeather = 60;
const int SwimmingWeather = 72;
const int WickedCold = 0;

Notice, however, that this process is somewhat cumbersome; also, this syntax doesn’t show any logical connection among these various constants—they’re just a set of unrelated values. You know that these constants all refer to temperature, but the compiler has no way of knowing that. C# provides an alternative construct, the enumeration, which allows you to group logically related constants, as in the following:

enum Temperatures
{
   WickedCold = 0,
   FreezingPoint = 32,
   LightJacketWeather = 60,
   SwimmingWeather = 72,
   BoilingPoint = 212,
}

Tip

The entries in the enumeration are separated by commas. Many programmers like to leave a comma after the last entry in an enumeration as a convenience for adding more values later. Other programmers find this, at best, sloppy. The code will compile either way.

The syntax for specifying an enumeration uses the enum keyword, as follows:

enum identifier [:base-type]{enumerator-list};

Tip

In a specification statement such as the preceding example, the square brackets indicate an optional element. Thus, you can declare an enum with no base type, simply by leaving it out (leave out the square brackets as well).

There are also optional attributes and modifiers you can use, but you don’t need them right now. An enumeration begins with the keyword enum, which is generally followed by an identifier; in this case, Temperatures:

enum Temperatures

The base type is the underlying type for the enumeration. You might specify that you are declaring constant ints, constant longs, or something else. If you leave out this optional value (and often you will), it defaults to int, but you are free to use any of the integral types (ushort, long) except for char. For example, the following fragment declares an enumeration with unsigned integers (uint) as the base type:

enum ServingSizes : uint
{
   Small = 1,
   Regular = 2,
   Large = 3
}

Notice that an enum declaration ends with the enumerator list, which contains the constant assignments for the enumeration, each separated by a comma. Example 3-5 rewrites Example 3-4 to use an enumeration.

Example 3-5. An enumeration represents a set of values that you don’t want to change while your program is running

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example_3_5_ _ _ _Enumerations
{
    class Values
    {
        // declare the enumeration
        enum Temperatures
        {
            WickedCold = 0,
            FreezingPoint = 32,
            LightJacketWeather = 60,
            SwimmingWeather = 72,
            BoilingPoint = 212,
        }

        static void Main( )
        {
            System.Console.WriteLine("Freezing point of water: {0}",
                                     (int)Temperatures.FreezingPoint);
            System.Console.WriteLine("Boiling point of water: {0}",
                                     (int)Temperatures.BoilingPoint);
        }
    }
}

In Example 3-5, you declare an enumerated constant called Temperatures. When you want to use any of the values in an enumeration in a program, the values of the enumeration must be qualified by the enumeration name. That is, you can’t just refer to FreezingPoint; instead, you use the enumeration identifier (Temperature) followed by the dot operator and then the enumerated constant (FreezingPoint). This is called qualifying the identifier FreezingPoint. Thus, to refer to the FreezingPoint, you use the full identifier Temperature.FreezingPoint.

You might want to display the value of an enumerated constant to the console, as in the following:

Console.WriteLine("The freezing point of water is {0}",
                  (int) Temperature.FreezingPoint);

To make this work properly, you must cast the constant to its underlying type (int). In this case, you are saying, “Treat this enumerated constant as an int.” Because you know the underlying type is int, this is safe to do. (See “Casting” earlier in this chapter.)

In Example 3-5, the values in the two enumerated constants FreezingPoint and BoilingPoint are both cast to type int; then that integer value is passed to WriteLine( ) and displayed.

Each constant in an enumeration corresponds to a numerical value. In Example 3-5, each enumerated value is an integer. If you don’t specifically set it otherwise, the enumeration begins at 0 and each subsequent value counts up from the previous. Thus, if you create the following enumeration:

enum SomeValues
{
   First,
   Second,
   Third = 20,
   Fourth
}

the value of First will be 0, Second will be 1, Third will be 20, and Fourth will be 21.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset