Variables

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

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 runtime. In addition, C# is type-safe, which, with the help of runtime checking, ensures that a variable can be operated on only via the correct type (except in unsafe blocks; see Section 2.17.2).

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 initalize 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
  }
}

The compiler generates a warning whenever a default value is assigned to a field ...

Get C# Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.