#37 – All Value Types Have a Default Constructor

All built-in value types in C# support a default (parameterless) constructor using the new keyword.  The default constructor allows you to instantiate an object such that it takes on a default value.

You’d normally instantiate one of the built-in types by giving  the associated variable a value.  But it’s also possible to use the new keyword to cause the variable to take on a default value.

 int i;          // Not instantiated yet
 int n1 = 12;    // Instanatiated, w/value of 12
 int n2 = new int();   // Instantiated, w/default value

The default values for the built-in value types are:

  • bool type = false
  • Numeric types (e.g. int, float) = 0 or 0.0
  • char type = single empty character
  • DateTime type = 1/1/0001 12:00:00 AM

#31 – Value Types and Reference Types

All types in C#, whether built-in or user-defined custom types, can be categorized as either value types or reference types.

  • Value types
    • Derive from System.ValueType (which derives from System.Object)
    • Allocated on the stack  (unless declared inside a reference type)
    • Value type variable contains value directly
    • Assignment makes a copy of the value
    • Passed by value (a copy is made)
    • Not garbage collected–die when they go out of scope
    • Either struct or enum
    • Sealed–can’t inherit from them
  • Reference types
    • Derive from System.Object or another reference type
    • Allocated on the heap
    • Reference type variable contains a reference (pointer) to the object’s contents (or contains null)
    • Assignment creates a new reference to the original object
    • Passed by reference  (pointer to object is passed)
    • Garbage collected
    • One of: class, delegate, array or interface
    • Support inheritance