Professional C# 6 and .NET Core 1.0. Christian Nagel
Чтение книги онлайн.

Читать онлайн книгу Professional C# 6 and .NET Core 1.0 - Christian Nagel страница 23

СКАЧАТЬ style="font-size:15px;">      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 for loop, while is a pretest loop. The syntax is similar, but while loops take only one expression:

      Unlike the for loop, the while loop is most often used to repeat a statement or a block of statements for a number of times that is not known before the loop begins. Usually, a statement inside the while loop’s body will set a Boolean flag to false on a certain iteration, triggering the end of the loop, as in the following example:

      The do..while Loop

      The do…while loop is the post-test version of the while loop. This means that the loop’s test condition is evaluated after the body of the loop has been executed. Consequently, do…while loops are useful for situations in which a block of statements must be executed at least one time, as in this example:

      The foreach Loop

      The foreach loop enables you to iterate through each item in a collection. For now, don’t worry about exactly what a collection is (it is explained fully in Chapter 11, “Collections”); just understand that it is an object that represents a list of objects. Technically, for an object to count as a collection, it must support an interface called IEnumerable. Examples of collections include C# arrays, the collection classes in the System.Collections namespaces, and user-defined collection classes. You can get an idea of the syntax of foreach from the following code, if you assume that arrayOfInts is (unsurprisingly) an array of ints:

      Here, foreach steps through the array one element at a time. With each element, it places the value of the element in the int variable called temp and then performs an iteration of the loop.

      Here is another situation where you can use type inference. The foreach loop would become the following:

      temp would be inferred to int because that is what the collection item type is.

      An important point to note with foreach is that you can’t change the value of the item in the collection (temp in the preceding code), so code such as the following will not compile:

СКАЧАТЬ