C# Interview Question #80
What are init-only properties and the required modifier in modern C#?
Memory Management & Modern C# Mid-Level Intermediate
Quick Interview Answer
An init accessor allows a property to be assigned during object initialization but prevents normal reassignment afterward. This supports immutable-style object models.
Detailed Explanation
An init accessor allows a property to be assigned during object initialization but prevents normal reassignment afterward. This supports immutable-style object models.
The required modifier indicates that callers must initialize a member when creating the object, unless a constructor or other compiler-recognized mechanism satisfies the requirement.
These features are useful for DTOs, configuration objects, commands, and domain models where required data should be explicit and accidental mutation should be reduced.
Code Example
public class CreateProductRequest
{
public required string Name { get; init; }
public decimal Price { get; init; }
}
var request = new CreateProductRequest
{
Name = "Laptop",
Price = 1200
};