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

Читать онлайн.
Название Professional C# 6 and .NET Core 1.0
Автор произведения Christian Nagel
Жанр Зарубежная образовательная литература
Серия
Издательство Зарубежная образовательная литература
Год выпуска 0
isbn 9781119096634



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

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# makes a fundamental distinction between variables that are declared at the type level (fields) and variables that are declared within methods (local variables).

      Consider the following code snippet (code file VariableScopeSample3/Program.cs):

      This code will compile even though you have two variables named j in scope within the Main method: the j that was defined at the class level and doesn’t go out of scope until the class Program is destroyed (when the Main method terminates and the program ends), and the j defined within Main. In this case, the new variable named j that you declare in the Main method hides the class-level variable with the same name, so when you run this code, the number 30 is displayed.

      What if you want to refer to the class-level variable? You can actually refer to fields of a class or struct from outside the object, using the syntax object.fieldname. In the previous example, you are accessing a static field (you find out what this means in the next section) from a static method, so you can’t use an instance of the class; you just use the name of the class itself:

      If you are accessing an instance field (a field that belongs to a specific instance of the class), you need to use the this keyword instead.

      Working with Constants

      As the name implies, a constant is a variable whose value cannot be changed throughout its lifetime. Prefixing a variable with the const keyword when it is declared and initialized designates that variable as a constant:

      Constants have the following characteristics:

      • They must be initialized when they are declared. After a value has been assigned, it can never be overwritten.

      • The value of a constant must be computable at compile time. Therefore, you can’t initialize a constant with a value taken from a variable. If you need to do this, you must use a read-only field (this is explained in Chapter 3).

      • Constants are always implicitly static. However, notice that you don’t have to (and, in fact, are not permitted to) include the static modifier in the constant declaration.

      At least three advantages exist for using constants in your programs:

      • Constants make your programs easier to read by replacing magic numbers and strings with readable names whose values are easy to understand.

      • Constants make your programs easier to modify. For example, assume that you have a SalesTax constant in one of your C# programs, and that constant is assigned a value of 6 percent. If the sales tax rate changes later, you can modify the behavior of all tax calculations simply by assigning a new value to the constant; you don’t have to hunt through your code for the value .06 and change each one, hoping you will find all of them.

      • Constants help prevent mistakes in your programs. If you attempt to assign another value to a constant somewhere in your program other than at the point where the constant is declared, the compiler flags the error.

Using Predefined Data Types

      Now that you have seen how to declare variables and constants, let’s take a closer look at the data types available in C#. As you will