only for RuBoard - do not distribute or recompile Previous Section Next Section

2.3 Variables

A variable represents a typed storage location. A variable can be a local variable, a parameter, an array element (see Section 2.11 later in this chapter), an instance field, or a static field (see Section 2.9.2 later in this chapter).

Every variable has an associated type, which essentially defines the possible values the variable can have and the operations that can be performed on that variable. C# is strongly typed, which means the set of operations that can be performed on a type is enforced at compile time, rather than at runtime. In addition, C# is type-safe, which, with the help of runtime checking, ensures that a variable can be operated only via the correct type (except in unsafe blocks; see Section 2.17.2 later in this chapter).

2.3.1 Definite Assignment

Variables in C# (except in unsafe contexts) must be assigned a value before they are used. A variable is either explicitly assigned a value or automatically assigned a default value. Automatic assignment occurs for static fields, class instance fields, and array elements not explicitly assigned a value. For example:

using System;
class Test {
  int v;
  // Constructors that initialize an instance of a Test
  public Test(  ) {} // v will be automatically assigned to 0
  public Test(int a) { // explicitly assign v a value
     v = a;
  }
  static void Main(  ) {
    Test[] iarr = new Test [2]; // declare array
    Console.WriteLine(iarr[1]); // ok, elements assigned to null
    Test t;
    Console.WriteLine(t); // error, t not assigned
  }
}

2.3.2 Default Values

The following table shows that, essentially, the default value for all primitive (or atomic) types is zero:

Type

Default value

Numeric

0

Bool

false

Char

'\0'

Enum

0

Reference

null

The default value for each field in a complex (or composite) type is one of these aforementioned values.

only for RuBoard - do not distribute or recompile Previous Section Next Section