Название | Professional C# 6 and .NET Core 1.0 |
---|---|
Автор произведения | Christian Nagel |
Жанр | Зарубежная образовательная литература |
Серия | |
Издательство | Зарубежная образовательная литература |
Год выпуска | 0 |
isbn | 9781119096634 |
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:
If you need to iterate through the items in a collection and change their values, you must use a for loop instead.
Jump Statements
C# provides a number of statements that enable you to jump immediately to another line in the program. The first of these is, of course, the notorious goto statement.
The goto Statement
The goto statement enables you to jump directly to another specified line in the program, indicated by a label (this is just an identifier followed by a colon):
A couple of restrictions are involved with goto. You can’t jump into a block of code such as a for loop, you can’t jump out of a class, and you can’t exit a finally block after try…catch blocks (Chapter 14, “Errors and Exceptions,” looks at exception handling with try.catch.finally).
The reputation of the goto statement probably precedes it, and in most circumstances, its use is sternly frowned upon. In general, it certainly doesn’t conform to good object-oriented programming practices.
The break Statement
You have already met the break statement briefly – when you used it to exit from a case in a switch statement. In fact, break can also be used to exit from for, foreach, while, or do…while loops. Control switches to the statement immediately after the end of the loop.
If the statement occurs in a nested loop, control switches to the end of the innermost loop. If the break occurs outside a switch statement or a loop, a compile-time error occurs.
The continue Statement
The continue statement is similar to break, and you must use it within a for, foreach, while, or do…while loop. However, it exits only from the current iteration of the loop, meaning that execution restarts at the beginning of the next iteration of the loop rather than restarting outside the loop altogether.
The return Statement
The return statement is used to exit a method of a class, returning control to the caller of the method. If the method has a return type, return must return a value of this type; otherwise, if the method returns void, you should use return without an expression.
An enumeration is a user-defined integer type. When you declare an enumeration, you specify a set of acceptable values that instances of that enumeration can contain. Not only that, but you can also give the values user-friendly names. If, somewhere in your code, you attempt to assign a value that is not in the acceptable set of values to an instance of that enumeration, the compiler flags an error.
Creating an enumeration can save you a lot of time and headaches in the long run. At least three benefits exist to using enumerations instead of plain integers:
• As mentioned, enumerations make your code easier to maintain by helping to ensure that your variables are assigned only legitimate, anticipated values.
• Enumerations make your code clearer by allowing you to refer to integer values by descriptive names rather than by obscure “magic” numbers.
• Enumerations make your code easier to type. When you begin to assign a value to an instance of an enumerated type, Visual Studio 2015 uses IntelliSense to pop up a list box of acceptable values to save you some keystrokes and remind you of the possible options.
You can define an enumeration as follows:
In this case, you use an integer value to represent each period of the day in the enumeration. You can now access these values as members of the enumeration. For example, TimeOfDay.Morning returns the value 0. You will typically use this enumeration to pass an appropriate value into a method and iterate through the possible values in a switch statement (code file EnumerationSample/Program.cs):
The real power of enums in C# is that behind the scenes they are instantiated as structs derived from the base class – System.Enum. This means it is possible to call methods against them to perform some useful tasks. Note that because of the way the .NET Framework is implemented, no performance loss is associated with treating the enums syntactically as structs. In practice, after your code is compiled, enums exist as primitive types, just like int and float.
You can retrieve the string representation of an enum, as in the following example, using the earlier TimeOfDay enum:
This returns the string Afternoon.
Alternatively, you can obtain an enum value from a string:
The preceding code snippet illustrates both obtaining an enum value from a string and converting to an integer. To convert from a string, you need to use the static Enum.Parse method, which, as shown, takes three parameters. The first is the type of enum you want to consider. The syntax is the keyword typeof followed by the name of the enum class in brackets. (Chapter 8 explores the typeof operator in more detail.) The second parameter is the string to be converted, and the third parameter is a bool indicating whether case should be ignored while the conversion is done. Finally, note that Enum.Parse actually returns an object reference – you need to explicitly convert this to the required enum type (this is an example of an unboxing operation). For the preceding code, this returns the value 1 as an object, corresponding to the enum value of TimeOfDay.Afternoon. Converting explicitly to an int, this produces the value 1 again.
Other methods