C# Data Types & Hierarchy

Comprehensive guide to value types, reference types, and their relationships

Value Types

Value types directly contain their data. Each variable has its own copy of the data, and operations on one variable do not affect another.

Definition

Value types are types that store their data directly in the memory location where the variable is allocated. They are stored on the stack unless they are part of a reference type.

Common Value Types:

int
32-bit signed integer
float
32-bit floating point
double
64-bit floating point
char
16-bit Unicode character
bool
Boolean (true/false) value
struct
User-defined value type
enum
Set of named constants
decimal
128-bit precise decimal
int number = 42;
float price = 19.99f;
char grade = 'A';
bool isValid = true;
struct Point { public int X, Y; }
enum Days { Sunday, Monday, Tuesday }

Memory Allocation

Value types are typically allocated on the stack, which makes them faster to access but limited in lifetime to the scope in which they are declared.

Note

When a value type is part of a class (reference type), it is stored on the heap along with the class instance.

Reference Types

Reference types store a reference to the memory location where the data is stored, rather than the data itself.

Definition

Reference types store the memory address of the data rather than the data itself. Multiple variables can reference the same data, and operations through one variable affect the data accessed by other references.

Common Reference Types:

string
Sequence of characters
object
Base type of all types
class
User-defined reference type
interface
Contract for classes
delegate
Reference to a method
array
Collection of elements
dynamic
Type determined at runtime
string name = "C# Programming";
object obj = name; // implicit conversion
class Person { public string Name; }
interface ILogger { void Log(string message); }
delegate void NotifyCallback(string message);
int[] numbers = new int[] {1, 2, 3};

Memory Allocation

Reference types are allocated on the managed heap. The stack contains a reference (memory address) to the actual object on the heap.

Note

The garbage collector automatically manages memory for reference types, freeing objects that are no longer referenced.

Type Hierarchy Diagram

C# has a unified type system where all types ultimately inherit from System.Object

C# Type Hierarchy

Key Points:

Code Examples

Value Type Behavior

// Value types: each variable has its own copy
int a = 10;
int b = a; // Copy of the value
b = 20; // Only b changes, a remains 10
Console.WriteLine($"a: {a}, b: {b}"); // Output: a: 10, b: 20

Reference Type Behavior

// Reference types: variables reference the same object
int[] arr1 = new int[] {1, 2, 3};
int[] arr2 = arr1; // Both reference the same array
arr2[0] = 100; // Modifies the array referenced by both variables
Console.WriteLine($"arr1[0]: {arr1[0]}"); // Output: arr1[0]: 100
Back to Dashboard