Parentheses are a useful tool for making your code easier to understand and
debug. Unless an expression is so simple that it’s obvious how it is evaluated,
add parentheses to make the result clear.
CONSTANTS
A constant is a lot like a variable except you must assign it a value when you declare it and you can-
not change the value later.
Syntactically a constant’s declaration is similar to a variable except it uses the keyword
const.
For example, the following code declares a
decimal constant named taxRate and assigns it the
value
0.09M. It then uses the constant in a calculation.
const decimal taxRate = 0.09M;
decimal subtotal = decimal.Parse(subtotalTextBox.Text);
decimal salesTax = taxRate * subTotal;
decimal grandTotal = subTotal + salesTax;
Constants work just like literal values so you could replace the constant taxRate with the literal
value
0.09M in the preceding calculation. Using a constant makes the code easier to read, however.
When you see the value
0.09M, you need to remember or guess that this is a tax rate.
Not only can it be hard to remember what this kind of “magic number” means, but it can also make
changing the value difficult if it appears in many places throughout the program. Suppose the code
uses the value
0.09M in several places. If the sales tax rate went up, you would have to hunt down all
of the occurrences of that number and change them. If you miss some of them, you could get very
confusing results.
Note that constants can contain calculated values as long as C# can perform the calculation before
the program actually runs. For example, the following code declares a constant that defines the
number of centimeters per inch. It then uses that value to define the number of centimeter per foot.
const double cmPerInch = 2.54;
const double cmPerFoot = cmPerInch * 12;
TRY IT
In this Try It you make some simple calculations. You take values entered by the user, convert
them into numbers, do some multiplication and addition, and display the results.
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them in the Lesson11 folder in the download.
596906c11.indd 145 4/7/10 12:32:36 PM