👉 Read the full lesson on DevLadder (free, lesson 4 of 38 in the C# Language: Basics to Advanced course)
| 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 |
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); // 99
Continue reading the lesson →
An interview question on C# Language
What are boxing and unboxing? Why avoid them?
Boxing converts a value type to object (or an interface) by allocating a heap object and copying the value; unboxing casts it back to the exact value type. It costs an allocation, a copy and GC pressure. Typical sources: non-generic collections (ArrayList), string.Format with value-type arguments on old APIs, calling interface methods on structs via the interface. Generics remove most boxing.
Can you answer these?
- What is the difference between
==and.Equals()? - What are
ref,outandinparameters? - Explain
IEnumerable,ICollection,IListandIQueryable. - What are delegates and events? How do they differ?
The answers, plus 22 more C# Language interview questions and a mock-interview mode, are free on DevLadder.
Next in the course: Variables, constants and operators →
Top comments (0)