Types: value vs referenceClasses, structs, and records
No narration yet
Module 3 · Lesson 114 min

Classes, structs, and records

C# has two families of types, and TS has one. A reference type (class) lives on the heap; a variable holds a reference to it, and two variables can point at the same object. A value type (struct) is copied by value; assigning it makes a fresh copy. Every object in JS/TS behaves like a reference type, so this distinction is new.

Then there's the record, which is the one you'll reach for most on the backend. A record is a reference type (usually) that the compiler gives value equality: two records are equal when their properties are equal, not when they're the same instance. That's the behaviour you probably assumed objects had coming from a world of deep-equal and immutable data. It's also concise: a positional record declares its shape in one line.

The three, side by side
// reference type: identity equality, mutable by default
public class Flight { public string Number { get; set; } = ""; }

// value type: copied on assignment
public struct Coord { public double Lat; public double Lng; }

// record: reference type WITH value equality, made for data
public record EjError(string Field, string Message);

var a = new EjError("Value", "required");
var b = new EjError("Value", "required");
// a == b is TRUE for the record. For the class it would be false.

EjError above is real Fusion domain code. It's a record because two errors with the same field and message are the same error; you never care which instance you're holding. That's the tell for reaching for a record: it's data, defined by its values, and you want equality and immutability to come for free.

Practice

Try it yourself

Do

Prove record equality

See the difference between class identity and record value equality with your own eyes.

Tick every step to confirm you did it.

Quiz

Pick the right type

You need a type for an immutable disruption error carried as data through the domain. Which do you declare?