Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Programming · C# · Chapter 10 / 10

Programming learning path

Runtime, memory, GC & equality

C# runs on the .NET managed runtime. Understanding object lifetime and value/reference semantics is more useful than memorizing the oversimplified rule that value types are always on the stack and reference types are always on the heap.

Garbage collection

The garbage collector tracks managed object reachability and reclaims objects that are no longer reachable. It uses generations because most objects are short-lived. GC timing is nondeterministic, which is why disposable resources still need Dispose/using.

Boxing and unboxing

Boxing converts a value type to object or an implemented interface, creating a boxed copy represented as a reference-type object. Unboxing extracts the value type again.

int number = 42;
object boxed = number;   // boxing
int copy = (int)boxed;   // unboxing

Equality

Reference equality asks whether two references point to the same object. Value equality asks whether their contents should be considered equal. Ordinary classes use reference-oriented equality by default unless they customize it; records provide value equality by default.

var first = new object();
var same = first;
Console.WriteLine(ReferenceEquals(first, same)); // True

var p1 = new Point(1, 2);
var p2 = new Point(1, 2);
Console.WriteLine(p1 == p2); // True

public record Point(int X, int Y);

Key points

  • GC manages managed object memory; it does not replace deterministic disposal.
  • Value/reference type is primarily a semantic distinction about copying and identity, not a guaranteed physical storage location.
  • Boxing creates a reference-type representation/copy of a value type.
  • ==, Equals and ReferenceEquals are not universally the same equality operation.

Source registry

2 chapter references
The C# type system

Value/reference types, nullability, conversions and type-system fundamentals

Microsoft Learn · Official documentation
Source ↗
Fundamentals of garbage collection

Managed heap, generations, collection and object lifetime

Microsoft Learn · Official documentation
Source ↗