C# & CLR Internals (50 Qs)•Part 1: Core Language, CLR & Memory Architecture (1 - 10)
What are Primary Constructors, Records, and `with` expressions in C# 10/12?
senior LevelCode ExampleSystem Design
In Simple Words:
- Records: Reference types or structs with built-in value-based equality (
Equals,GetHashCode), immutability, and automatic deconstruction. withexpressions: Non-destructive mutation (creates a shallow copy with modified properties).- Primary Constructors (C# 12): Declare constructor parameters directly in the class or struct definition header, auto-assigning fields.
csharp
// C# 12 Primary Constructor with Record:
public record UserDto(Guid Id, string Email, string Role);
// Non-destructive mutation using 'with':
var user1 = new UserDto(Guid.NewGuid(), "dev@company.com", "Engineer");
var user2 = user1 with { Role = "Staff Engineer" };
// Value-based equality:
bool areEqual = (user1 == user2); // false (different Role)