C# Feature – Required members
Overview
Section titled “Overview”required
enforces that specified members must be set during object initialization.
Introduced In
Section titled “Introduced In”C# 11 (2022)
Before
Section titled “Before”public class User { public string Email { get; set; } /* risk of missing init */ }
public class User { public required string Email { get; init; } }var u = new User { Email = "a@b.com" }; // required
Annotated Example
Section titled “Annotated Example”public record Customer(string Id){ public required string Name { get; init; }}
Gotchas & Best Practices
Section titled “Gotchas & Best Practices”- Use with
init
for immutable models.
Related Features
Section titled “Related Features”Version history
Section titled “Version history”- C# 11:
required
introduced. - C# 12+: Works smoothly with primary constructors.