Professional C# 6 and .NET Core 1.0. Christian Nagel

Чтение книги онлайн.

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

Professional C# 6 and .NET Core 1.0 - Christian Nagel

Скачать книгу

href="#i000007000000.png"/>

      To declare variables of different types, you need to use separate statements. You cannot assign different data types within a multiple-variable declaration:

      Notice the // and the text after it in the preceding examples. These are comments. The // character sequence tells the compiler to ignore the text that follows on this line because it is included for a human to better understand the program; it’s not part of the program itself. Comments are explained further later in this chapter in the “Using Comments” section.

      Initializing Variables

      Variable initialization demonstrates an example of C#’s emphasis on safety. Briefly, the C# compiler requires that any variable be initialized with some starting value before you refer to that variable in an operation. Most modern compilers will flag violations of this as a warning, but the ever-vigilant C# compiler treats such violations as errors. This prevents you from unintentionally retrieving junk values from memory left over from other programs.

      C# has two methods for ensuring that variables are initialized before use:

      • Variables that are fields in a class or struct, if not initialized explicitly, are by default zeroed out when they are created (classes and structs are discussed later).

      • Variables that are local to a method must be explicitly initialized in your code prior to any statements in which their values are used. In this case, the initialization doesn’t have to happen when the variable is declared, but the compiler checks all possible paths through the method and flags an error if it detects any possibility of the value of a local variable being used before it is initialized.

      For example, you can’t do the following in C#:

      Notice that this code snippet demonstrates defining Main so that it returns an int instead of void.

      If you attempt to compile the preceding lines, you receive this error message:

      Consider the following statement:

      In C#, this line of code would create only a reference for a Something object, but this reference would not yet actually refer to any object. Any attempt to call a method or property against this variable would result in an error.

      To instantiate a reference object in C#, you must use the new keyword. You create a reference as shown in the previous example and then point the reference at an object allocated on the heap using the new keyword:

      Using Type Inference

      Type inference makes use of the var keyword. The syntax for declaring the variable changes by using the var keyword instead of the real type. The compiler “infers” what the type of the variable is by what the variable is initialized to. For example:

      becomes:

      Even though someNumber is never declared as being an int, the compiler figures this out and someNumber is an int for as long as it is in scope. Once compiled, the two preceding statements are equal.

      Here is a short program to demonstrate (code file VariablesSample/Program.cs):

      The output from this program is as follows:

      There are a few rules that you need to follow:

      • The variable must be initialized. Otherwise, the compiler doesn’t have anything from which to infer the type.

      • The initializer cannot be null.

      • The initializer must be an expression.

      • You can’t set the initializer to an object unless you create a new object in the initializer.

      Chapter 3, “Objects and Types,” examines these rules more closely in the discussion of anonymous types.

      After the variable has been declared and the type inferred, the variable’s type cannot be changed. When established, the variable’s type strong typing rules that any assignment to this variable must follow the inferred type.

      Understanding Variable Scope

      The scope of a variable is the region of code from which the variable can be accessed. In general, the scope is determined by the following rules:

      • A field (also known as a member variable) of a class is in scope for as long as its containing class is in scope.

      • A local variable is in scope until a closing brace indicates the end of the block statement or method in which it was declared.

      • A local variable that is declared in a for, while, or similar statement is in scope in the body of that loop.

      Scope Clashes for Local Variables

      It’s common in a large program to use the same variable name for different variables in different parts of the program. This is fine as long as the variables are scoped to completely different parts of the program so that there is no possibility for ambiguity. However, bear in mind that local variables with the same name can’t be declared twice in the same scope. For example, you can’t do this:

      Consider the following code sample (code file VariableScopeSample/Program.cs):

      This code simply prints out the numbers from 0 to 9, and then back again from 9 to 0, using two for loops. The important thing to note is that you declare the variable i twice in this code, within the same method. You can do this because i is declared in two separate loops, so each i variable is local to its own loop.

      Here’s another example (code file VariableScopeSample2/Program.cs):

      If you try to compile this, you’ll get an error like the following:

      This occurs because the variable j, which is defined before the start of the for loop, is still in scope within the for loop and won’t go out of scope until the Main method has finished executing. Although the second j (the illegal one) is in the loop’s scope, that scope is nested within the Main method’s scope. The compiler has no way to distinguish between these two variables, so it won’t allow the second one to be declared.

      Scope Clashes for Fields and Local Variables

      In certain circumstances, however, you can distinguish between two identifiers with the same name (although not the same fully qualified name) and the same scope, and in this case the compiler allows you to declare the second variable. That’s because C#

Скачать книгу