
Beginning ASP.NET 2.0 With CSharp (2006) [eng]
.pdf
Chapter 9
So if a number % 2 is 0, then it’s even.
Like concatenation, operators can be combined with assignment. In order to add 1 to a number, you can do this:
int n1 = 4;
n1 = n1 + 1;
This says take n1, add 1 to it, and assign that value back to n1. Remember that assignment works by taking the value on the right of the = and assigning that to the variable of the left of the =. This works even if the variable being assigned is on the right because the right side is calculated first. An alternative to this is to combine operators:
int n1 = 4;
n1 += 1;
This has the same result as the first example although it looks very different. In fact it’s just a shortcut that allows the addition operator to be combined with the assignment. It simply says take the n1 variable and add 1 to it. The other arithmetic operators can be used in the same way.
The subtraction operator is also used for negation, like so:
int n1; int n2;
n1 |
= |
-3; |
|
n2 |
= |
-n1; |
// results in: 3 |
Negation can be used on any numeric type.
Comparison Operators
Comparison is how decisions are made in code. You’ll find out about the mechanism of that in due time, but for now, all you need to know is that the operators define what comparison is made. The comparison operators are shown in the following table:
Operator |
Action |
|
|
< |
Less than |
<= |
Less than or equal to |
> |
Greater than |
>= |
Greater than or equal to |
== |
Equal to |
!= |
Not equal to |
|
|
308

Code
Comparison always involves an expression — the term for all operators and operands involved in the comparison. The result of a comparison expression is a Boolean value — it is either true or false. You look at the mechanics of using expressions in decisions in a while, but these operators work just like the ones you’ve already seen. If you have two variables, n1 with a value of 4 and n2 with a value of 5, the following could be used as expressions:
n1 |
> |
n2 |
// |
results |
in: |
false |
n2 |
> |
n1 |
// |
results |
in: |
true |
For numbers, the comparison is obvious, but for other data types it might not be. Dates, for example, work in a similar way, but the test is whether one date is earlier or later than another. For example:
DateTime d1 |
= new DateTime(2005, 10, 1); |
// |
1 |
October |
2005 |
DateTime d2 |
= new DateTime(2004. 1, 2); |
// |
2 |
January |
2004 |
d1 > d2 |
// results in: true |
||||
|
|
|
|
|
|
The greater than operator tests to see if the first date is later than the second, so the result is true. For equality tests, two ==s are used together:
if (d1 == d2)
The same comparison operators are used with objects, but with objects, you check to see if two object references point at the same object. The != operator does the opposite, checking to see if two object references point at different objects. This is useful when you’re dealing with objects, and many of the scenarios where this is used are covered in later chapters. However, it’s worth showing an example here. Because the concept of databases has already been covered, we can use that in this example. When you use the data controls on pages, you get a lot of functionality by just dropping a control onto a page and setting a few properties, but there are occasions where you need to explicitly deal with a database, and this becomes truer as you gain experience and write more complex applications. The checkout for Wrox United is one case, where the items from the shopping cart are written to the database. For this a SqlConnection object is used, which provides a way to connect to a specific database. For example:
SqlConnection conn = new SqlConnection(“ . . .”); conn.Open();
// insert the checkout items
conn.Close();
This code fragment opens a database connection, inserts the checkout items, and then closes the connection. However, if there is an error when opening the connection, the conn variable wouldn’t contain an active connection, so the Close would fail. This is where object tests are used, so the Close could be modified to the following:
if (conn != null)
conn.Close();
If an error occurs, conn wouldn’t be assigned a value and would be null, so conn is tested before being closed. If it is not null, the connection can be closed. You’ll learn more about this topic in Chapter 15.
309

Chapter 9
Logical Operators
Logical operators allow the combination of expressions. The operators are as follows:
Operator |
Actiond |
|
|
&& |
True if both sides of the expression are true. |
|| |
True if either side of the expression is true, or if both sides of the |
|
expression are true. |
^ |
True if only one side of the expression is true. |
! |
Negates the expression. |
|
|
All except ! require two expressions, in the following form:
LeftExpression Operator RightExpression
The following table should make the result more obvious.
Operator |
LeftExpression |
RightExpression |
Result |
|
|
|
|
&& |
true |
true |
true |
|
true |
false |
false |
|
false |
true |
false |
|
false |
false |
false |
|
|
|
|
|| |
true |
true |
true |
|
true |
false |
true |
|
false |
true |
true |
|
false |
false |
false |
|
|
|
|
^ |
true |
true |
false |
|
true |
false |
true |
|
false |
true |
true |
|
false |
false |
false |
|
|
|
|
One important thing to know about testing expressions is that when you have multiple expressions, not all of them might be evaluated because expression testing can stop if one of the expressions can guarantee a result. For example, consider the following code:
310

Code
string Name = “Dave”;
if (Name == “Dave” || Name == “Dan”)
{
// name is either Dave or Dan
}
Here, Name is first checked to see if it is Dave. It is, so the second expression (the check for Dan) is never done — it’s not needed because it won’t affect the result. For example, imagine instead of a simple test for a name, you called a function that updated a database:
if (User.IsInRole(“Admin”) && UserAudit(“Admin”)) Then ‘ user is an admin and their details have been updated
End If
This would only call the UserAudit function if the user is in the Admin role. Using && means that if the first part of the test fails, there is no point evaluating the second part, so it is never run.
Another time when this is useful is when you need to see if a property of an object has a value — you only want to check if the object actually exists, not if it is set to null. For example, consider the following code, where data is fetched from a database and then some action needs to be performed only if some rows were returned:
SqlDataReader rdr;
rdr = DataLayer.GetProducts();
if (rdr != null && rdr.HasRows)
Assume that the database access fails for some reason, and rdr is set to a null value — that is, null. First the check for null is done, and this test returns false — rdr is null — and because it is false, the second test isn’t done. There’s no need because the first is false and the entire expression can never be true.
Operator Precedence
Operators aren’t limited to just one or two expressions, and they can be combined in a multitude of ways. Before doing this, however, you need to understand that there is an order of precedence, so the result you get might not be what you expected. This is the same as the order of preference you learned in math all those years ago. Consider this simple expression:
1 + 2 * 3
This returns 7 because multiplication has a higher precedence than addition. You can use parentheses to force a change in order:
(1 + 2) * 3
This returns 9 because the expression in parentheses is evaluated first. It’s always a good idea to include parentheses in your expressions because it makes your intentions clear, and this is certainly a good thing when you (or someone else) looks at your code later.
311

Chapter 9
If you don’t use parentheses, the order of precedence is as follows, in descending order:
Unary negation (-)
Multiplication and division (*, /)
Modulus (%)
Addition and subtraction (+, -) and string concatenation (+)
Arithmetic bitshift (<<, >>)
Comparison (=, <>, <, <=, >, <=)
Negation (!)
Conjunction (&&)
Disjunction (||, ^)
This chapter hasn’t covered all of these operators because some of them you won’t use very often, or they are used in more advanced techniques. They were included in the preceding list just so that you know where they fit into the order.
Decisions
Decisions are how you make code react to data, usually from a database or user input. You’ve already seen plenty of decisions throughout the book, and in this chapter, logical operators covered how expressions play an important part of the decision-making process. Decisions can be made in two ways, and which way you use depends on the number of values an expression can be. For example, if an expression can return one of two values (true or false), the if statement is used. If the decision is a selection among a number of choices (perhaps the delivery method from the Wrox United shop), the switch statement is used.
Single Selections
Single selections are based on the if statement, which always has two parts. The first is the expression being tested, which will result in a true or false value, and the expression is always contained with parenthesis. The second is the block of code to be executed if the expression is true. The syntax is as follows:
if (condition)
// code to run if condition is true
This syntax is suitable if there is only one line of code to run if the condition is true. If there are multiple lines of code, you need to enclose the lines of code within curly brackets. For example:
if (condition)
{
//code to run if condition is true
//more code to run
//yet more code
}
312

Code
The preceding two examples test a single condition and only run code if the condition is true. It is important to understand that the multiple lines of code to be run must be enclosed within curly brackets — the indentation doesn’t have anything to do with the actual code run. For example, consider the following:
if (User.IsAuthenticated) MemberDiscount = 0.01; JoinFlag = true;
In the preceding code, if the IsAuthenticated property of the User object is true, then the MemberDiscount is set to 10%. Even though the JoinFlag line is indented the same as the member discount line, it is not part of the if statement — JoinFlag will always be set to true, whether or not the user is authenticated. In effect, this code is as follows:
if (User.IsAuthenticated) MemberDiscount = 0.01;
JoinFlag = true;
To ensure that both lines are part of the if statement, they should be enclosed within curly brackets:
if (User.IsAuthenticated)
{
MemberDiscount = 0.01; JoinFlag = true;
}
Some people use these curly brackets even if they only have a single line of code to be run for the if statement. It doesn’t slow the code down at all, and it does make your intentions explicitly clear. For example:
if (User.IsAuthenticated)
{
MemberDiscount = 0.01;
}
JoinFlag = true;
Another form of selection is as follows:
if (condition)
//code to run if condition is true
else
//code to run if the condition is false
This tests a single condition but has code for both the true and false situations. This is only suitable if both the true and false pieces of code have a single line to run, but the use of the curly braces can be used in either of the code blocks:
if (condition)
{
//code to run if condition is true
//more code to run
}
else
// code to run if the condition is false
313

Chapter 9
Alternatively, you could write the following:
if (condition)
//code to run if condition is true
else
{
//code to run if the condition is false
//more code to run
}
Yet another way you could write it is as follows:
if (condition)
{
//code to run if condition is true
//more code to run
}
else
{
//code to run if the condition is false
//more code to run
}
All of these examples show an either/or situation, with just two blocks of code. For multiple tests, you can use the following:
if (condition)
//code to run if condition is true else if (condition1)
//code to run if condition1 is true
else
//code to run if no conditions were true
There can be any number of else if conditions.
Consider Wrox United, where the club sends out a newsletter, but only to those fan club members who have ticked the check box when they entered their details. The user settings are stored in the Profile object, which was shown in Chapter 5:
if (Profile.Mailings == true)
// send the newsletter to this person
This is a simple case, where there is only one expression being tested, and one set of code to run.
If some code needs to be run when the expression is false, the else statement can be used:
if (Profile.Mailings == true)
//send the newsletter to this person
else
//don’t send the newsletter
314

Code
The else and if statements can be used together to choose among several different expressions. For example:
if (Profile.IsNewUser)
// send introductory mail
else if (Profile.Mailings == true)
//send the newsletter to this person
else
//don’t send the newsletter
In this example, the expressions first check to see if the member is a new user — that is, if they have only just joined and haven’t had any mailings yet. If so, the introductory mail is sent. If the first expression is false, that is they aren’t a new user, then the next expression is checked — do they require mailings? If so, then that code block is run, and if none of the expressions are true, the else block is run. If a condition tests true, the appropriate code block is run and no more conditions are tested — the if statement ends.
Multiple Selections
For selections where the expression can be one of a number of possible answers, the if statement can become unwieldy. For example, consider the Wrox United shop where you can buy a range of branded merchandise. Currently items are sent using the standard postal service, but what if the club wanted to offer different delivery methods, perhaps by way of a drop-down list:
string[] delivery = {“Next Day Post”, “3 Day Post”, “Courier”, “International”}; DeliveryDropDownList.DataSource = delivery;
DeliveryDropDownList.DataBind();
Maybe the data is from an array, or more likely from a database where the delivery type and associated cost are both included. When the total price is calculated, though, different action needs to be taken — perhaps to instruct the packing department which box type to use, or maybe to interface directly with the delivery company’s tracking system. Using the if statement would result in the following code:
string del = DeliveryDropDownList.SelectedValue; if (del == “Next Day Post”)
//pack in a normal box and stick lots of stamps on it else if (del == “3 Day post”)
//pack in a normal box and stick one stamp on it
else if (del == “Courier”)
//pack in a courier specific box and book a pickup
Else
//pack in a large create and take to the freight company
You can see that all those else if statements and the layout make this hard to read. In situations like this, it’s best to use the switch statement, which would turn the preceding code into the following:
switch (DeliveryDropDownList.SelectedValue)
{
case “Next Day Post”:
// pack in a normal box and stick lots of stamps on it break;
case “3 Day post”:
315

Chapter 9
// pack in a normal box and stick one stamp on it break;
case “Courier”:
// pack in a courier specific box and book a pickup break;
default:
// pack in a large create and take to the freight company break;
}
This code is much neater, easier to read, and less error prone. It works in a similar way to the previous example, where the expression is on the first line — the selected value from the drop-down list. This is then compared to each of the values in the case statements, starting at the top and working down. The first match causes the code block under that case statement to be executed, and all other case statements are ignored. If there is no match, the code block under the default statement is run.
The switch statement allows matching multiple selections or ranges. The syntax for this is as follows:
switch (condition)
{
case test1: case test2:
// code to run if condition matches test1 or test2 break;
case test3: case test4: case test5:
// code to run if condition matches test3, test4, or test5 break;
default:
// code to run if the condition matches no tests break;
}
In this syntax, the same block of code will be run for tests 1 and 2, as will the same code for tests 3, 4, and 5. Anything that doesn’t match these tests will run the code under the default section.
Loops
Loops provide a way to repeat actions, either a fixed number of times or until some condition is met. The decision of which loop to use depends on whether you know in advance how many times you need to loop, or whether some external factor influences this. For example, when a DataReader object provides a way to read through some records from a database, this has a Read method that returns false when there are no more records. This is a case of not knowing in advance the number of times you need to loop.
316

Code
The while Loop
To perform looping until some condition is met, you can use the While or Do loops, both of which are dependent upon an expression. Take the While loop first, using the case of data from a database:
SqlConnection conn = new SqlConnection(“...”);
SqlCommand cmd = new SqlCommand(“SELECT * FROM Products”, conn);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
// do something with the data record
}
rdr.Close();
Ignore the SQL statement, because it’s not that important for this example. All that’s important is that a number of records will be returned when the SQL command is run. This statement is simple — the while loop continues execution of its code block while the condition is true. The Read method returns true if it has a record, and false if it doesn’t, so this loop continues until there are no more records. So, the first time the while statement is encountered, the expression is tested. If it is true, the code in the while block is executed, and when the closing curly bracket (}) is encountered, the loop starts again, testing the expression once more. This continues until the expression is false, in which case, processing continues with the statement after the closing curly bracket. This happens regardless of the initial value of the condition, so if the condition is initially false, the contents of the loop are never executed.
If you need to stop processing a loop, that is, break out of it in the middle, you can use the break statement. For example:
while (rdr.Read())
{
if (rdr[“ItemCost”] < 0) break;
}
Like the if statement, while can be used without curly braces if the code to be run consists of only a single line. For example:
while (rdr.Read())
Console.WriteLine(rdr[“Column1”].ToString());
Because the code block only consists of a single line, no brackets are needed. However, this could be written as follows:
while (rdr.Read())
{
Console.WriteLine(rdr[“Column1”].ToString());
}
317