Roadmap › C# Language — Basics to Advanced › Module: Getting Started
Lessons in this course (38)
4. Value types vs reference types
Basic★ Must knowLesson 4 of 38
| Value types | Reference types | |
|---|---|---|
| Examples | int, double, bool, char, decimal, struct, enum, DateTime | class, string, arrays, delegate, interface, record (class) |
| Variable holds | The data itself | A reference (address) to an object on the heap |
| Assignment | Copies the value | Copies the reference — both point to the same object |
| Default | 0, false, ... | null |
| Stored | Inline: on the stack for locals, inside the containing object for fields | Object on the managed heap |
csharp
struct Point { public int X; }
class Box { public int X; }
var p1 = new Point { X = 1 };
var p2 = p1; // copy
p2.X = 99;
Console.WriteLine(p1.X); // 1
var b1 = new Box { X = 1 };
var b2 = b1; // same object
b2.X = 99;
Console.WriteLine(b1.X); // 99Interview tip: "Value types live on the stack" is only partly true. A value-type field inside a class lives on the heap with that object. Say: value types are stored inline where they are declared.