
.NET 1.1+C# Constants and Enumerations
The forty-eighth part of the C# Fundamentals tutorial examines the use of constants and enumerations. These provide two methods of describing non-changing values using descriptive words rather than "magic numbers" to improve code readability.
Why Use Constants?
A constant is similar to a variable as it defines a name for a value. However, a constant differs from a variable because once defined, the value assigned to the constant cannot be changed. The benefit of constants is their assistance in creating self-documenting code. They also allow you to declare key values in a single place, permitting easy maintenance should the value need to be updated and the software recompiled.
To demonstrate the self-documenting value of constants, consider the following line of code:
price += (price * 0.175) + 4.99;
You could probably work out what the developer was trying to do here. A price is being increased by 17.5% and then a further £4.99 is being added. However, if the code is rewritten using constants instead of magic numbers, the purpose becomes obvious.
price += (price * ValueAddedTax) + DeliveryCharge;
Not only is this second code sample easier to read, it allows the definitions of tax rules and delivery charges to be changed in a single location. The constants can be modified once and the new values automatically be updated throughout your code. NB: The scope of a constant is defined in a similar manner to variable scopes.
Declaring a Constant
Constants are declared using similar syntax to other variables but with the const prefix . Here is how the previous example code looks with the constant definitions included:
double price = 100;
const double ValueAddedTax = 0.175;
const double DeliveryCharge = 4.99;
price += (price * ValueAddedTax) + DeliveryCharge;
Constants must be possible to evaluate at compile-time. This limits the use of constants to values that can be expressed directly in the source code, such as numeric values and strings. Values that cannot be initialised without a constructor are not permitted, meaning reference type constants may only be null.
16 August 2007