Explain the difference between value types and reference types in C#.

6 minbeginner.NETvalue-typesreference-types

Quick Answer

Value types store data directly on the stack, contain actual data, and copying creates a new copy. Reference types store data on the heap with variables holding references/pointers, and copying creates a new reference to the same object. Value types include int, struct, enum; reference types include class, string, arrays.

Detailed Answer

Value Types:

  • Stored directly on the stack (or inline in containing types)
  • Contain the actual data directly
  • Each variable has its own copy of the data
  • When you copy a value type, you copy the actual data
  • Examples: int, double, bool, struct, enum, decimal, DateTime
  • Derive from System.ValueType
  • Cannot be null (unless nullable value type like int?)

Reference Types:

  • Stored on the heap
  • Variable contains a reference (pointer) to the actual data
  • Multiple variables can reference the same object
  • When you copy a reference type, you copy the reference, not the data
  • Examples: class, interface, delegate, string, object, arrays
  • Derive from System.Object
  • Can be null

Key Differences Illustrated:

Value Type Example:

int a = 10;
int b = a;  // Creates a COPY of the value
b = 20;
Console.WriteLine(a);  // Output: 10 (unchanged)
Console.WriteLine(b);  // Output: 20

Reference Type Example:

class Person { public string Name { get; set; } }

Person person1 = new Person { Name = "John" };
Person person2 = person1;  // Copies the REFERENCE, not the object
person2.Name = "Jane";

Console.WriteLine(person1.Name);  // Output: "Jane" (changed!)
Console.WriteLine(person2.Name);  // Output: "Jane"
// Both variables point to the same object in memory

Memory Allocation:

  • Value types are typically faster to allocate/deallocate (stack allocation)
  • Reference types require heap allocation and garbage collection
  • Value types have less memory overhead (no object header)

Performance Implications:

  • Use value types for small, simple data structures
  • Use reference types when you need shared references or large data
  • Boxing occurs when converting value type to reference type (performance cost)