Field Initialization

C# automatically initializes class fields to default values.  The assigned default value depends on the field’s type
(integer, string, etc.)


// C# automatically sets all member variables to a safe default value.
class DefaultValues
{

  // Here are a number of fields and the corresponding defaults

  private sbyte   theSignedByte;  // = 0
  private byte    theByte;        // = 0
  private short   theShort;       // = 0
  private int     theInt;         // = 0
  private long    theLong;        // = 0
  private char    theChar;        // = 0
  private float   theFloat;       // = 0.0
  private double  theDouble;      // = 0.0
  private bool    theBool;        // = false
  private decimal theDecimal;     // = 0
  private string  theStr;         // = null
  private object  theObj;         // = null
}


You can also initialize fields in the class declaration.  This is helpful if a field should default to a value that is
different from the runtime-supplied default.  


// This technique is useful when you don’t want to use the supplied
// default values and don’t want to write the same code in each ctor.

public class Test
{
  private int myInt = 90;
  private string myStr = "My initial value";
  private Employee myEmp = new Employee();
}


In contrast, local variables in a method scope do not receive automatic default assignments.  You will need to set
the variable to an initial value before use, or else you will receive a compile time error.


public static void MyMethod()
{

 // Error!  myInt is not assigned an initial value before use!

 int myInt;
 myInt++;

 // OK!  myBool is assigned an initial value before use.

 bool myBool = true;
 Console.WriteLine("myBool has the value of: " + myBool);
}


Field Initialization
Table of Contents
C# Tutorial | C#.NET Tutorial | Field Initialization Tutorial

Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used
exclusively as an online learning aid.  Any attempts to copy, reproduce, or use for training is
strictly prohibited.
Courseware
Training Resources
Tutorials
Services