132
LESSON 11 Using Variables and Performing CalCUlations
You can use double quotes to surround strings and single quotes to surround chars as in the
following code:
string firstName = “William”;
string lastName = “Gates”;
char middleInitial = ‘H’;
Sometimes you might like to include a special character such as a carriage return or tab character in
a string literal. Unfortunately, you can’t simply type a carriage return into a string because it would
start a new line of code.
To work around this dilemma, C# provides escape sequences that represent special characters. An
escape sequence is a sequence of characters that represent a special character such as a carriage
return or tab.
Table 11-3 lists C#’s escape sequences.
TABLE 113
SEQUENCE MEANING
a
Bell

Backspace
f
Formfeed
Newline
Carriage return
Horizontal tab
v
Vertical tab
Single quotation mark
Double quotation mark
\
Backslash
?
Question mark
OOO
ASCII character in octal
xhh
ASCII character in hexadecimal
xhhhh
Unicode character in hexadecimal
For example, the following code makes a variable that refers to a string that contains quotes and a
newline character:
string txt = “Unknown value “ten.“ Please enter a number.”;
596906c11.indd 132 4/7/10 12:32:32 PM
Type Conversions
133
When you display this string in a MessageBox, the user sees text similar to the following:
Unknown value “ten.”
Please enter a number.
When you display text in a Label (or MessageBox), you can start a new line by
using the newline character (
). When you display text in a TextBox, however,
you must start a new line by using the carriage return and newline characters
together (
). (The sequence also works for Labels and MessageBoxes.)
C# also provides a special verbatim string literal that makes using some special characters
easier. This kind of value begins with
@“ and ends with a corresponding closing quote . Between
the quotes, the literal doesn’t know anything about escape sequences and treats every character
literally.
A verbatim string literal cannot contain a double quote because that would end the string. It can’t even
use an escaped double quote because verbatim string literals don’t understand escape sequences.
Verbatim string literals are very useful if you need a string that contains a lot of backslashes such
as a Windows directory path (C:ToolsBinarySourceC#PrintInvoices) or that needs to describe
escape sequences themselves (“Use rn to start a new line”).
Verbatim string literals can even include embedded new lines (which they represent as ) and tab
characters, although those may make your code harder to read.
TYPE CONVERSIONS
C# performs implicit data type conversions where it knows the conversion is safe. For example, the
following code declares a
long variable and sets it equal to the int value 6. Because an int can always
fit in a
long, C# knows this is safe and doesn’t complain.
long numBananas = 6;
The converse is not always true, however. A long value cannot always fit in an int variable. Because
it cannot know for certain that any given
long will fit in an int, C# wont quietly sit by while your
code assigns a
long value to an int.
For example, the following code assigns a value to a
long variable. It then tries to save that long
value into an
int variable. At this point, C# panics and flags the line as an error.
long numBananas = 6;
int numFruits = numBananas;
In cases such as this, you can use three methods to coerce C# into converting data from one type to
another: casting, converting, and parsing.
596906c11.indd 133 4/7/10 12:32:32 PM
134
LESSON 11 Using Variables and Performing CalCUlations
Casting
To cast a value from one data type to another, you put the target data type inside parentheses in front
of the value. For example, the following code explicitly converts the variable
numBananas into an int:
long numBananas = 6;
int numFruits = (int)numBananas;
Casting works only between compatible data types. For example, because double and int are both
numbers, you can try to cast between them. (When you cast from a
double to an int, the cast simply
discards any fractional part of the value with no rounding.) In contrast, the
string and bool data
types are not compatible with the numeric data types or each other so you cannot cast between them.
Normally a cast doesn’t check whether it can succeed. If you try to convert a
long into an int and
the
long won’t fit, C# sweeps its mistake under the rug like a politician in an election year, and the
program keeps running. The value that gets shoved into the
int may be gibberish, but the program
doesnt crash.
If the
int now contains garbage, any calculations you perform with it will also be garbage so, in
many cases, it’s better to let your program throw a tantrum and crash. (Lesson 21 explains how to
catch errors such as this so you can do something more constructive than merely crashing.)
To make C# flag casting errors, surround the cast in parentheses and add the word
checked in front
as in the following code:
long worldPopulation = 6800000000;
int peopleInWorld = checked((int)worldPopulation);
Now when the code executes at run time, the program will fail on the second statement.
If you have several statements that you want to check, you can make a checked
block. In the following code, all of the statements between the curly braces are
checked.
long worldPopulation = 6800000000;
long asiaPopulation = 4000000000;
checked
{
int peopleInWorld = (int)worldPopulation;
int peopleInAsia = (int)asiaPopulation;
}
The checked keyword also checks integer calculations for overow. For example,
if you multiply two huge
int variables together, the result won’t fit in an int.
Normally the program keeps running without complaint even though the result
overowed, so it isn’t what you expect.
If you are working with values that might overow and you want to be sure the
results make sense, protect the calculations with
checked.
596906c11.indd 134 4/7/10 12:32:32 PM
Type Conversions
135
Converting
Casting only works between compatible types. The Convert utility class (which is provided by the
.NET Framework) gives you methods that you can use to try to convert values even if the data types
are incompatible. These are shared methods provided by the
Convert class itself, so you don’t need
to create an instance of the class to use them.
For example, the
bool and int data types are not compatible, so C# doesn’t let you cast from one
to the other. Occasionally, however, you might want to convert an
int into a bool or vice versa.
In that case you can use the
Convert class’s ToBoolean and ToInt32 methods. (You use ToInt32
because
ints are 32-bit integers.)
The following code declares two
int variables and assigns them values. It uses Convert to change
them into
bools and then changes one of them back into an int.
int trueInt = -1;
int falseInt = 0;
bool trueBool = Convert.ToBoolean(trueInt);
bool falseBool = Convert.ToBoolean(falseInt);
int anotherTrueInt = Convert.ToInt32(trueBool);
When you treat integer values as a Booleans, the value 0 is false and all other
values are true. If you convert
true into an integer value, you get –1.
In a particularly common scenario, a program must convert text entered by the user into some other
data type such as an
int or decimal. The following uses the Convert.ToInt32 method to convert
whatever the user entered in the
ageTextBox into an int:
int age = Convert.ToInt32(ageTextBox.Text);
This conversion works only if the user enters a value that can be reasonably converted into an int. If
the user enters 13, 914, or –1, the conversion works. If the user enters “seven,” the conversion fails.
Converting text into another data type is more properly an example of parsing than of data type
conversion, however. So while the
Convert methods work, your code will be easier to read and
understand if you use the parsing methods described in the next section.
Parsing
Trying to find structure and meaning in text is called parsing. All of the simple data types (int,
double, decimal) provide a method that converts text into that data type. For example, the int
data type’s
Parse method takes a string as a parameter and returns an int; at least it does if the
string contains an integer value.
The following code declares a
decimal variable named salary, uses the decimals Parse method to
convert the value in the
salaryTextBox into a decimal, and saves the result in the variable:
decimal salary = decimal.Parse(salaryTextBox.Text);
596906c11.indd 135 4/7/10 12:32:33 PM
136
LESSON 11 Using Variables and Performing CalCUlations
As is the case with the Convert methods, this works only if the text can reasonably be converted
into a
decimal. If the user types “12,345.67,” the parsing works. If the user types “ten” or “1.2.3,
the parsing fails.
Unfortunately C#s conversion and parsing methods get confused by some for-
mats that you might expect them to understand. For example, they can’t handle
currency characters, so they fail on strings like “$12.34” and “e54.32.
You can tell the decimal class’s Parse method to allow currency values by passing it a second param-
eter as shown in the following code.
decimal salary = decimal.Parse(txt, System.Globalization.NumberStyles.Any);
PERFORMING CALCULATIONS
You’ve already seen several pieces of code that assign a value to a variable. For example, the following
code converts the text in the
salaryTextBox into a decimal and saves it in the variable salary:
decimal salary = decimal.Parse(salaryTextBox.Text);
More generally, you can save a value that is the result of a more complex calculation into a variable
to the left of an equals sign. Fortunately, the syntax for these kinds of calculations is usually easy to
understand. The following code calculates the value 2736 + 7281 / 3 and saves the result in the exist-
ing variable named
result:
double result = 2736 + 7281 / 3;
The operands (the values used in the expression) can be literal values, values stored in variables,
or the results of methods. For example, the following code calculates the sales tax on a purchase’s
subtotal. It multiplies the tax rate stored in the
taxRate variable by the decimal value stored in the
subtotalTextBox and saves the result in the variable salesTax.
salesTax = taxRate * decimal.Parse(subtotalTextBox.Text);
Note that a variable can appear on both sides of the equals sign. In that case, the value on the
right is the variable’s current value and, after the calculation, the new result is saved back in
the same variable.
For example, the following code takes
xs current value, doubles it, adds 10, and saves the result back
in variable
x. If x started with the value 3, then when this statement finishes x holds the value 16.
x = 2 * x + 10;
A variable may appear more than once on the right side of the equals sign but it can appear only
once on the left.
The following sections provide some additional details about performing calculations.
596906c11.indd 136 4/7/10 12:32:33 PM
..................Content has been hidden....................

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