Cook Computing

Variable Initialization in C#

September 11, 2004 Written by Charles Cook

In this post yesterday I stated that the C# compiler does not allow the use of uninitialized variables. As David Buck pointed out in the comments to his post I linked to, this only applies to temporary variables and not instance variables. However instance variables are automatically initialized to known values. The C# spec says:

The following categories of variables are automatically initialized to their default values:

  • Static variables.
  • Instance variables of class instances.
  • Array elements.

The default value of a variable depends on the type of the variable and is determined as follows:

  • For a variable of a value-type, the default value is the same as the value computed by the value-types default constructor (11.1.1).
  • For a variable of a reference-type, the default value is null.

Note: Initialization to default values is typically done by having the memory manager or garbage collector initialize memory to all-bits-zero before it is allocated for use. For this reason, it is convenient to use all-bits-zero to represent the null reference. end note

Compare this with C++ where there is no initialization of instance variables. This leads to a particularly insidious form of bug where code will seem to run successfully because the memory allocated to uninitialized variables just happens by chance to have values which don't cause any obvious problems. Either the program runs incorrectly or at some point blows up in an arbitrary way. I've seen many bugs caused by this and its not really acceptable in a language used for general purpose development.