Value Types

Overview

  • Stored on the stack.
  • Contain a value, not a reference.
  • Inherit from System.Value
  • Exists of built-in types, user-defined types and enumerations.
  • Prefer to use Int32 (int) and Double (double) for counters/floating numbers. These are optimized by the framework/hardware.
  • Nullable types have .HasValue and .Value properties to determine if they have been set.
    • Console.WriteLine( (myBool.HasValue) ? myBool.Value.ToString() : “not set” );
  • Structures are value types as well, user-defined value types.
  • Enums are stored as value types, and primarily used for code readability.
  • object.GetType().IsValueType returns true for value types.

Good practice

  • Always define the value of a value type upon declaration.
    • Initialize it to null if needed.
    • The use of nullable types can help to enable bool variables to store null.
      • Nullable<bool> myBool = null;
      • bool? myBool = null;
      • Read Nullable<T> Usage Guidelines however, to avoid using a bool as a tri-state switch.
  • Use structures for objects which represent a single combined value, which is smaller then 16 bytes.
  • Structures should be immutable.
  • Don't define a default constructor on a structure.

Examples

Value types vs Reference types

// ---------------------------------------------------------------------------------------------
// Example of value types holding a value instead of a reference.
// ---------------------------------------------------------------------------------------------
 
int a, b;
a = 5;  // Store 5 in a
b = a;  // Copy the value of a into b, instead of holding a reference
a = 10; // Store 10 in a, will not affect the value of b, since it's been copied.
Console.WriteLine(a); // Will print 10
Console.WriteLine(b); // Will print 5

Nullable Types

Nullable<bool> myBool = null;           
Console.WriteLine((myBool.HasValue) ? myBool.Value.ToString() : "not set");
myBool = true;
Console.WriteLine((myBool.HasValue) ? myBool.Value.ToString() : "not set");

Structures

struct MyPoint
{
    private int _x;
    private int _y;
 
    public int X
    {
        get { return this._x; }
    }
 
    public int Y
    {
        get { return this._y; }
    }
 
    public MyPoint(int x, int y)
    {
        this._x = x;
        this._y = y;
    }
}

Enums

enum TestEnum : int
{
    Value1,
    Value2
}
 
static void Main(string[] args)
{
    TestEnum en = TestEnum.Value1;
    Console.WriteLine((int)en + " : " + en);
}