Название | Professional C# 6 and .NET Core 1.0 |
---|---|
Автор произведения | Christian Nagel |
Жанр | Зарубежная образовательная литература |
Серия | |
Издательство | Зарубежная образовательная литература |
Год выпуска | 0 |
isbn | 9781119096634 |
Another point to note about the if statement is that you don’t need to use the braces when there’s only one statement in the conditional branch:
However, for consistency, many programmers prefer to use curly braces whenever they use an if statement.
TIP Not using curly braces with if statements can lead to errors in maintaining the code. It happens too often that a second statement is added to the if statement that runs no matter whether the if returns true or false. Using curly braces every time avoids this coding error.
A good guideline in regard to the if statement is to allow programmers to not use curly braces only when the statement is written in the same line as the if statement. With this guideline, programmers are less likely to add a second statement without adding curly braces.
The if statements presented also illustrate some of the C# operators that compare values. Note in particular that C# uses == to compare variables for equality. Do not use = for this purpose. A single = is used to assign values.
In C#, the expression in the if clause must evaluate to a Boolean. It is not possible to test an integer directly (returned from a function, for example). You have to convert the integer that is returned to a Boolean true or false, for example, by comparing the value with zero or null:
The switch Statement
The switch / case statement is good for selecting one branch of execution from a set of mutually exclusive ones. It takes the form of a switch argument followed by a series of case clauses. When the expression in the switch argument evaluates to one of the values beside a case clause, the code immediately following the case clause executes. This is one example for which you don’t need to use curly braces to join statements into blocks; instead, you mark the end of the code for each case using the break statement. You can also include a default case in the switch statement, which executes if the expression doesn’t evaluate to any of the other cases. The following switch statement tests the value of the integerA variable:
Note that the case values must be constant expressions; variables are not permitted.
Though the switch.case statement should be familiar to C and C++ programmers, C#’s switch.case is a bit safer than its C++ equivalent. Specifically, it prohibits fall-through conditions in almost all cases. This means that if a case clause is fired early on in the block, later clauses cannot be fired unless you use a goto statement to indicate that you want them fired, too. The compiler enforces this restriction by flagging every case clause that is not equipped with a break statement as an error:
Although it is true that fall-through behavior is desirable in a limited number of situations, in the vast majority of cases it is unintended and results in a logical error that’s hard to spot. Isn’t it better to code for the norm rather than for the exception?
By getting creative with goto statements, you can duplicate fall-through functionality in your switch.cases. However, if you find yourself really wanting to, you probably should reconsider your approach. The following code illustrates both how to use goto to simulate fall-through, and how messy the resultant code can be:
There is one exception to the no-fall-through rule, however, in that you can fall through from one case to the next if that case is empty. This allows you to treat two or more cases in an identical way (without the need for goto statements):
One intriguing point about the switch statement in C# is that the order of the cases doesn’t matter – you can even put the default case first! As a result, no two cases can be the same. This includes different constants that have the same value, so you can’t, for example, do this:
The previous code also shows another way in which the switch statement is different in C# compared to C++: In C#, you are allowed to use a string as the variable being tested.
Loops
C# provides four different loops (for, while, do..while, and foreach) that enable you to execute a block of code repeatedly until a certain condition is met.
The for Loop
C# for loops provide a mechanism for iterating through a loop whereby you test whether a particular condition holds true before you perform another iteration. The syntax is
where:
• The initializer is the expression evaluated before the first loop is executed (usually initializing a local variable as a loop counter).
• The condition is the expression checked before each new iteration of the loop (this must evaluate to true for another iteration to be performed).
• The iterator is an expression evaluated after each iteration (usually incrementing the loop counter).
The iterations end when the condition evaluates to false.
The for loop is a so-called pretest loop because the loop condition is evaluated before the loop statements are executed; therefore, the contents of the loop won’t be executed at all if the loop condition is false.
The for loop is excellent for repeating a statement or a block of statements for a predetermined number of times. The following example demonstrates typical usage of a for loop. It writes out all the integers from 0 to 99:
Here, you declare an int called i and initialize it to zero. This is used as the loop counter. You then immediately test whether it is less than 100. Because this condition evaluates to true, you execute the code in the loop, displaying the value 0. You then increment the counter by one, and walk through the process again. Looping ends when i reaches 100.
Actually, the way the preceding loop is written isn’t quite how you would normally write it. C# has a shorthand for adding 1 to a variable, so instead of i = i + 1, you can simply write i++:
You can also make use of type inference for the iteration variable i in the preceding example. Using type inference, the loop construct would be as follows:
It’s not unusual to nest for loops so that an inner loop executes once completely for each iteration of an outer loop. This approach is typically employed to loop through every element in a rectangular multidimensional array. The outermost loop loops through every row, and the inner loop loops through every column in a particular row. The following code displays rows of numbers. It also uses another Console method, Console.Write, which does the same thing as Console.WriteLine but doesn’t send a carriage return to the output (code file ForLoop/Program.cs):
Although j is an integer, it is automatically converted to a string so that the concatenation can take place.
The preceding sample results in this output:
It is technically possible to evaluate something other than a counter variable in a for loop’s test condition, but it is certainly not typical. It is also possible to omit one (or even all) of the expressions in the for loop. In such situations, however, you should consider using the while loop.
The while Loop
Like the