wasAsked.

Explain record types, init-only properties, and immutability in C#, including where they improve API design.

PhonePe · Full Stack Developer · 3-4-years · technical

Published

Year not specified · .NET, C#, Software Engineering

Community answers

Posted by wasAsked editorial collection

Records are data-focused types with generated value equality, readable `ToString`, and nondestructive mutation through `with`. An `init` accessor permits assignment during construction or object initialization but prevents normal reassignment afterward. These features reduce accidental mutation in DTOs, commands, configuration, and domain value objects. ```csharp public sealed record CreateOrder( Guid CustomerId, IReadOnlyList<OrderLine> Lines); public sealed record OrderLine { public required string Sku { get; init; } public required int Quantity { get; init; } public decimal UnitPrice { get; init; } } var original = new OrderLine { Sku = "COFFEE", Quantity = 1, UnitPrice = 120m }; var corrected = original with { Quantity = 2 }; ``` Immutability is not automatic all the way down: a record containing a mutable `List<T>` can still be changed, and record equality compares that list reference rather than each element. Prefer immutable collections or expose read-only abstractions, validate at the boundary, and use classes when identity and a controlled mutable lifecycle matter more than value equality.

Prince Yadav · · 0 likes

These C# features make it easier to create objects that do not change after construction. Records - record (reference type) and record struct (value type) give value-based equality: two records with the same property values are equal. - The compiler generates Equals, GetHashCode, ToString, a deconstructor and, for positional records, a constructor. - Non-destructive mutation with "with" creates a modified copy. public record Money(decimal Amount, string Currency); var price = new Money(100, "INR"); var discounted = price with { Amount = 90 }; // price is unchanged Console.WriteLine(price == new Money(100, "INR")); // True Init-only properties - init accessors can be set in an object initializer or constructor, but not afterwards. public class CreateOrderRequest { public required string CustomerId { get; init; } public required IReadOnlyList<OrderLine> Lines { get; init; } } The required keyword (C# 11) makes the compiler force callers to set those properties. Immutability caveats - Records are shallowly immutable. A record containing a List<T> can still have that list modified; use IReadOnlyList<T> or ImmutableArray<T>. - Positional record properties are init-only, but you can declare mutable properties inside a record if you choose, which breaks the guarantee. Where they improve API design - Request and response DTOs: concise, immutable and easy to compare in tests. - Value objects in the domain (Money, Email, DateRange) with validation in the constructor, so invalid instances cannot exist. - Messages and events, which should never change after publishing. - Thread safety: immutable objects can be shared across threads without locks. - Caching and dictionary keys, because values and hash codes cannot change after insertion. Where to be careful: EF Core entities are tracked and updated, so classes with identity-based equality usually suit them better than records.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics