We said back in Chapter 1 that trying to access 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 CS0165: 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 over-simplified, however, and we'd like 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 of 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.
}
}