Value Types
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
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);
}
You May Also Like
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



