O'Reilly logo

C# Language Pocket Reference by Ted Neward, Ben Albahari, Peter Drayton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Variables and Parameters

A variable represents a typed storage location. A variable can be a local variable, parameter, array element, instance field, or static field.

All variables have 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 are enforced at compile time rather than at runtime. In addition, C# is type-safe, which ensures that a variable can be operated on via the correct type only with the help of runtime checking (except in unsafe blocks).

Definite Assignment

All variables in C# 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[ ] tests = new Test [2]; // declare array
    Console.WriteLine(tests[1]); // ok, elements assigned
                                 // to null
    Test t;
    Console.WriteLine(t); // error, t not assigned before
                          // use
  }
}

Default Values

The default value for all primitive (or atomic) types is zero:

Type

Default value

Numeric types

0

Bool type

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required