Stop Null DTOs at Compile Time with C# Required Members
C# 11's required keyword forces callers to initialize non-nullable DTO properties in object initializers, catching missing assignments at compile time instead of runtime. Pair with init-only setters and SetsRequiredMembers for immutable, validated construction.
16 Aug 2026, 19:41 UTC

The Problem: Nullable DTOs Slip Through
You've enabled nullable reference types. You've marked properties as non-nullable. Yet a UserDto still reaches your service layer with Name = null because someone called new UserDto() without setting it. The compiler happily builds; the crash happens at runtime.
C# 11's required keyword moves that failure to compile time. It forces callers to initialize marked members in an object initializer, and the compiler verifies every required member is assigned before the object escapes the initializer.
Required Members in Practice
Mark a property with required and give it an init setter to keep the object immutable after construction:
public sealed class UserDto
{
public required string Name { get; init; }
public required string Email { get; init; }
public string? Bio { get; init; } // optional
}
Now this code fails to compile:
var dto = new UserDto { Email = "[contact removed]" };
// CS9035: Required member 'UserDto.Name' must be set in the object initializer
The error appears at the exact call site. No runtime validation, no custom analyzers, no reflection.
Combining with Constructors via SetsRequiredMembers
Sometimes you need a constructor—for factory methods, deserialization callbacks, or computed defaults. The compiler doesn't know your constructor assigns every required member, so it still warns that the object might be uninitialized. [SetsRequiredMembers] tells the compiler: "this constructor satisfies all required members."
using System.Diagnostics.CodeAnalysis;
public sealed class UserDto
{
public required string Name { get; init; }
public required string Email { get; init; }
[SetsRequiredMembers]
public UserDto(string name, string email)
{
Name = name;
Email = email;
}
}
With the attribute, new UserDto("Alice", "[contact removed]") compiles cleanly, but new UserDto { Email = "..." } still fails because Name is missing from the initializer. The attribute only suppresses the "object may be uninitialized" warning on the constructor itself; it does not relax the initializer requirement.
Worked Example: API Request DTO
Consider a minimal ASP.NET Core endpoint that binds JSON to a DTO:
app.MapPost("/users", (CreateUserRequest req) =>
{
// req.Name and req.Email are guaranteed non-null here
return Results.Ok(new { req.Name, req.Email });
});
public sealed class CreateUserRequest
{
public required string Name { get; init; }
public required string Email { get; init; }
public string? ReferralCode { get; init; }
}
If a client sends { "email": "[contact removed]" }, model binding creates the object via Activator.CreateInstance and then sets properties. The required keyword does not stop that—model binding bypasses the initializer syntax. You still need [Required] data annotations or FluentValidation for runtime safety. Required members protect your own code that constructs DTOs directly.
Trade-offs and Limitations
- Source-breaking change: Adding
requiredto an existing public type forces every caller to update their initializers. For published libraries, prefer optional members with constructors or factory methods. - Reflection and deserializers bypass it:
Activator.CreateInstance,JsonSerializer.Deserialize, and ORM materializers ignorerequired. Pair with runtime validation at trust boundaries. - Framework requirement: Needs C# 11 (langversion 11 or
latest) and .NET 7+. On older TFMs,SetsRequiredMembersAttributeis missing; you can define a copy inSystem.Diagnostics.CodeAnalysisif you must target netstandard2.0. - No inheritance of requirement: A derived class does not automatically inherit required members from its base. Each type declares its own contract.
Quick Verification Checklist
- Create a
net7.0console project with<LangVersion>latest</LangVersion>. - Add a class with
public required string Name { get; init; }. - Build without assigning
Namein an initializer—confirmCS9035. - Add a constructor that assigns
Name, decorate with[SetsRequiredMembers], rebuild—warning disappears, initializer omission still fails.
When to Adopt
Use required members for internal DTOs, command objects, and options classes that your code constructs directly. They give you compile-time null safety with the ergonomics of object initializers. Keep data annotations or validators for anything crossing a serialization boundary. The feature is small, focused, and already in the compiler you're using—no extra packages, no runtime cost.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.