Professional C# 6 and .NET Core 1.0. Christian Nagel
Чтение книги онлайн.
Читать онлайн книгу Professional C# 6 and .NET Core 1.0 - Christian Nagel страница 24
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 on System.Enum do things such as return the number of values in an enum definition or list the names of the values. Full details are in the MSDN documentation.
As discussed earlier in this chapter, namespaces provide a way to organize related classes and other types. Unlike a file or a component, a namespace is a logical, rather than a physical, grouping. When you define a class in a C# file, you can include it within a namespace definition. Later, when you define another class that performs related work in another file, you can include it within the same namespace, creating a logical grouping that indicates to other developers using the classes how they are related and used:
Placing a type in a namespace effectively gives that type a long name, consisting of the type’s namespace as a series of names separated with periods (.), terminating with the name of the class. In the preceding example, the full name of the Subscriber struct is CustomerPhoneBookApp.Subscriber. This enables distinct classes with the same short name to be used within the same program without ambiguity. This full name is often called the fully qualified name.
You can also nest namespaces within other namespaces, creating a hierarchical structure for your types:
Each namespace name is composed of the names of the namespaces it resides within, separated with periods, starting with the outermost namespace and ending with its own short name. Therefore, the full name for the ProCSharp namespace is Wrox.ProCSharp, and the full name of the NamespaceExample class is Wrox.ProCSharp.Basics.NamespaceExample.
You can use this syntax to organize the namespaces in your namespace