Records are reference types optimized for immutable data with value-based equality—concise DTOs without boilerplate. Structs are value types: copied on assignment, stack-friendly for small data—unlike reference classes and unlike manual stack discipline in C++.
Record syntax
record Point(int X, int Y);
var a = new Point(1, 2);
var b = a with { X = 3 }; // non-destructive copy
Records synthesize equality, ToString, and deconstruction. Use record struct for lightweight value-type records.
Struct basics
readonly struct Color(byte R, byte G, byte B);
Avoid large structs—copying cost grows with size. Default struct constructors zero-initialize fields.
Important interview questions and answers
- Q: Record vs class?
A: Records emphasize immutable data and value equality; classes suit mutable entities with identity. - Q: When use struct?
A: Small immutable value bundles (coordinates, keys)—not for polymorphic hierarchies or large payloads.
Self-check
- What does the with expression do on records?
- Are structs reference types?
Tip: Use record for immutable data shapes; use struct for small value types—avoid large structs that copy on every assignment.
Interview prep
- record vs class?
Records provide value-based equality and concise syntax for immutable data; classes use reference equality by default unless overridden.
- When use struct?
Small immutable value types (coordinates, IDs)—avoid large structs that copy on every assignment.