C# & CLR Internals (50 Qs)•Part 3: CLR Internals, Native AOT & Production Diagnostics (25 - 35)
Records and Immutability: `record class` vs `record struct`.
senior LevelCode ExamplecsharpCLR Internals
In Simple Words: Records are nominal types designed for immutable data:
- Auto-generates value-based equality (
Equals(),==), hash code, andToString(). initaccessors: Properties can only be assigned during object construction.- Non-destructive Mutation (
withexpression): Creates a new copy with modified properties while preserving the original.
csharp
public record User(string Id, string Email, int Age);
var user1 = new User("101", "alex@example.com", 28);
// Clones user1 with updated email; user1 remains completely unchanged!
var user2 = user1 with { Email = "alex.new@example.com" };