13.6. More on Fields

Now that we've gone into more detail on some of the generic collection classes available in the FCL, let's talk a little more about fields. Previous chapters of this book discussed fields, which are values or objects responsible for storing the data specific to a given object. In the earlier chapters, we glossed over some of the finer points. Let's now take a little time to flesh out a couple of the finer points about fields.

13.6.1. Initialization of Variables Revisited

We said back in Chapter 1 that trying to access local variables without explicitly initializing them will result in a compilation error. For example, this next bit of code

public class Example
{
  static void Main() {
      // Declare several local variables within the Main() method.
      int i;  // not automatically initialized
      int j;  // ditto
      j = i;  // compilation error!
    }
}

was shown to produce the following compilation error on the line that is highlighted in the snippet:

error: Use of unassigned local variable 'i'

We also stated in Chapter 3 that variables are implicitly assigned their zero-equivalent value in some situations, if we haven't explicitly assigned them a value. Both of these statements regarding initialization of variables were a bit oversimplified, however, and we want to correct the oversimplification now.

To properly understand the notion of initialization in C#, we must differentiate between local variables—that is, variables declared within a method, and whose scope is therefore limited to that method (recall our discussion of the scope of a variable in Chapter 1)—and fields of a class (whether instance or static variables), which are declared at the class scope level. As it turns out:

  • All local variables, of any type, are considered by the compiler to be uninitialized until they have been explicitly initialized within a program.

  • All fields, on the other hand, of any type, are automatically initialized to their zero-equivalent values—that is, bools are initialized to false, numerics to either 0 or 0.0, reference types to null, and so forth.

Here is an example illustrating all these points:

public class Student
{
  // Fields ARE automatically initialized.
						private int age;                 // initialized to 0

private double gpa;              // initialized to 0.0
						private bool isHonorsStudent;    // initialized to false
						private Professor myAdvisor;     // initialized to null
						// This includes STATIC variables.
						private static int studentCount;   // initialized to 0
         // etc.

         // Methods.
         public void UpdateGPA() {
           // Local variables are NOT automatically initialized.
						double val;   // NOT initialized - value is undefined.
						Course c;     // NOT initialized - value is undefined.
           // etc.
         }
       }

13.6.2. Implicitly Typed Local Variables

Local variables, those declared inside a method body, can be given the implicit type of var instead of an explicit type. The implicitly typed local variable must be initialized when it is declared, and the compiler infers what the variable type is based on the value to which it is initialized. Implicitly typed local variables can be used in for and foreach statements. Consider the following examples:

using System;
using System.Collections.Generic;

// This simple program shows some var syntax

public class VarDemo
{
  static void Main() {
    //  name is compiled as a string
    var name = "Lisa";

    //  names is compiled as a List<string>
    var names = new List<string>();

    // Use var in foreach statement
    foreach(var item in names ) {  //  var assumed to be a string
      //  Do something with item
    }
  }
}

The var keyword can only be applied to local variables and can't be used on fields declared at the class level. Implicitly typed local variables can't be used with the array initializer. The following examples of var won't compile:

public class VarDemo
{
  //  This won't compile; it's a class variable
  private var id = "111-11-111.dat";

  static void Main() {

    //  Can't use var with array initializer
    var names = { "Math 101", "Ballroom 262", "Physics 245" };
  }
}

Note that overuse of var can make your code hard to read. It's often a good idea to explicitly declare the type of a variable. The main use of var in C# is when working with Language-Integrated Query (LINQ) features—a subject beyond the scope of this book to discuss in detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset