Lesson 8: Value objects and records
When a price is just a decimal and a currency is just a string, nothing stops you from adding shekels to dollars or mutating an amount mid-calculation. In this lesson we build value objects with C# records — immutable values compared by value — so such mistakes are blocked at compile time.
A value object is like a 20-shekel banknote: it does not matter which exact note you got — only the value counts. And you cannot "edit" a note — only replace it with another one.
- Value object
- A value defined only by its data — two prices of 10 ILS are the same value, with no separate identity. Always immutable.
- record type
- A C# type where the compiler generates value equality (Equals/==), init-only properties, a constructor, and ToString from one declaration.
- immutability
- The object's state never changes after creation. A "change" is done with a with-expression — a new copy with the updated value, the original intact.