Overview
- Stored on the stack.
- Contain a value, not a reference.
- Inherit from System.ValueType.
- Consist of built-in types, user-defined types and enumerations.
- Prefer to use Int32 (int) and Double (double) for counters/floating-point 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.
- Use a nullable type if it needs to be able to hold null.
- Nullable types allow value types such as bool 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 than 16 bytes.
- Structures should be immutable.
- You can’t define a default (parameterless) constructor on a structure in C#.
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

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.




