CSharp/C# Tutorial - C# Variables






A variable represents a storage location for a modifiable value.

A variable can be a local variable, parameter, field, or array element.

Definite Assignment

C# enforces a definite assignment policy.

Local variables must be assigned to a value before using.

Method arguments must be supplied when a method is called.

All other variables are initialized by the runtime.

Fields and array elements are automatically initialized to default values for their type.

The following code outputs 0, since array elements are implicitly assigned to their default values:


static void Main() {
     int[] ints = new int[2];
     Console.WriteLine (ints[0]); // 0 
} 

The following code outputs 0, because fields are implicitly assigned a default value:


class Test {
     static int x;
     static void Main() { 
        Console.WriteLine (x); 
      } 
} 

The code above generates the following result.





Default Values

All type instances have a default value.

The following table lists the the default value for the predefined types:

TypeDefault value
All reference typesnull
All numeric and enum types0
char type'\0'
bool typefalse

We can get the default value for any type using the default keyword:


decimal d = default (decimal); 

The default value in a custom value type, for example struct, is the same as the default value for each field.