Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Required vs Init: Key Differences

C# required and init solve different initialization problems. Learn how they work, how to combine them for immutable objects, and when to choose each pattern.

~6 min readC#
#C##required modifier#init accessor#object initialization
Comparison of C# required and init modifiers showing compile-time enforcement and immutability

When you need to control how properties are initialized, C# gives you two related tools: required and init. They solve different problems. required enforces at compile time that a member is set during construction. init prevents a property from being changed after construction. Understanding the exact behavior of each is essential for designing clean, predictable APIs.

What Does the required Modifier Enforce?

The required modifier, introduced in C# 11, tells the compiler that a property or field must be initialized when an instance is constructed. This enforcement happens at compile time: the code will not build if a required member is not supplied. The value can be supplied in an object initializer, or by a constructor that is marked with [SetsRequiredMembers].

csharp
public class Product { public required string Name { get; set; } public required decimal Price { get; set; } }

With this definition, any code that creates a Product must set Name and Price. The following will not compile:

csharp
var product = new Product(); // Error: required member 'Product.Name' must be set

The required modifier is useful when you want to guarantee that certain data is always present after construction. It shifts responsibility from runtime checks to the compiler, reducing the chance of NullReferenceException or missing-value bugs.

What Does the init Accessor Allow?

The init accessor, introduced in C# 9, defines a property that can be set only during object initialization. After the object is constructed, the property becomes read-only. This is a building block for immutable objects.

csharp
public class Order { public string OrderId { get; init; } public DateTime CreatedAt { get; init; } }

An init-only property can be assigned in an object initializer or in a constructor, but not after the object has been created. For example:

csharp
var order = new Order { OrderId = "A100", CreatedAt = DateTime.UtcNow }; order.OrderId = "B200"; // Error: property is read-only after initialization

The init accessor gives you immutability without requiring a full constructor with parameters. It works naturally with object initializers, making the code more readable when many properties need to be set.

Comparing required and init in Practice

While required and init are often used together, they solve different problems. required enforces that a property is set; init enforces that it cannot be changed after construction. The table below summarizes the key differences:

Aspectrequiredinit
EnforcementCompile-time: must be setCompile-time: cannot be set later
ImmutabilityDoes not imply immutabilityMakes property read-only after init
Typical usageMandatory dataImmutable data
Allowed assignmentObject initializer, or constructor marked [SetsRequiredMembers]Constructor or object initializer
C# versionC# 11C# 9

You can use required without init to have a mutable property that must be initialized, or init without required to allow optional initialization. The two are orthogonal.

Combining required with init for Immutable Objects

A common pattern is to combine required and init to create immutable objects that guarantee all necessary fields are present. This gives you both compile-time validation and immutability.

csharp
public class Customer { public required string CustomerId { get; init; } public required string Email { get; init; } public string? DisplayName { get; init; } }

Here, CustomerId and Email must be set during initialization, and once set, they cannot change. DisplayName is optional but also immutable. This pattern is ideal for DTOs, configuration records, and value objects where the data should not change after creation.

When you combine these modifiers, object initializer syntax becomes the primary mechanism for satisfying the required contract unless a constructor is marked [SetsRequiredMembers]. This is particularly useful when you have many properties, as it avoids long constructor parameter lists and makes the code self-documenting.

Constructor Parameters vs Object Initializers

A constructor can assign init-only properties, and it can assign required members. The key difference is whether callers can satisfy the required contract without an object initializer. Mark a constructor with [SetsRequiredMembers] to tell the compiler that it initializes all required members:

csharp
using System.Diagnostics.CodeAnalysis; public class Invoice { public required string InvoiceNumber { get; init; } public required decimal Total { get; init; } [SetsRequiredMembers] public Invoice(string invoiceNumber, decimal total) { InvoiceNumber = invoiceNumber; Total = total; } }

With [SetsRequiredMembers], new Invoice("INV-1", 100m) is valid. Without the attribute, the compiler would still require those properties to be set in an object initializer, even though the constructor assigns them.

Object initializers are more readable when the number of properties is large, and they allow the caller to set only the properties they care about. Constructors are better when you need to perform additional logic during construction, such as validation or derived value computation. If you use a constructor to satisfy required members, keep the contract explicit with [SetsRequiredMembers].

Edge Cases: Inheritance, Serialization, and Anonymous Types

The required requirement is inherited. A derived class does not need to redeclare a base required member to keep it required, and it cannot remove the requirement. For example:

csharp
public class Base { public required string Name { get; set; } } public class Derived : Base { // Name is inherited, but still required }

If you hide a required member with new, the hiding member must also be marked required; otherwise, the compiler reports an error. This matters when designing class hierarchies.

Serialization frameworks also interact with these modifiers. System.Text.Json can set init-only properties during deserialization. For required members, the serializer expects those values in the JSON payload; a missing required member can cause a JsonException. Adding required to an existing model can therefore break older clients that send payloads without that field.

Anonymous types are always immutable and use init-like behavior, but they do not support required. If you need to enforce required members in a lightweight structure, consider using a record with required properties instead.

Choosing Between required and init for API Design

When designing a public API, the decision between required and init should be guided by the contract you want to establish with callers. Use required when a property is logically necessary for the object to function correctly. Use init when you want to prevent mutation after creation, even if the property is optional.

The combination of both is powerful for domain models and DTOs. It makes the object's invariants explicit at compile time and prevents accidental mutation later. However, be mindful of backward compatibility. Adding required to an existing property is a breaking change because existing code that constructs the object without setting that property will no longer compile. Adding init to a property that was previously settable is also breaking, as it removes the setter.

For internal code, the choice is less critical, but it still affects maintainability. Using required and init together reduces the number of runtime null checks and makes the codebase more predictable. The compiler acts as a guard, catching missing assignments early in the development cycle.

Runtime Behavior and Performance

Neither required nor init adds runtime validation. Both are enforced by compiler checks at the call site; there is no hidden initialization guard running when the object is created. In normal construction, the performance overhead is negligible.

The real benefit is in code quality and reliability. By moving initialization requirements to compile time, you eliminate a class of runtime errors that would otherwise surface as null reference exceptions or invalid object states. This is especially valuable in large codebases where objects are constructed in many places and the cost of a missing property can be high.

The compiler checks do not apply to reflection or dynamic code. For example, if you use Activator.CreateInstance to create an object without setting required properties, the instance will contain null or default values. required is enforced for statically compiled code, so if you rely on reflection-based construction, add runtime validation as a fallback.

Final Code Example: A Practical Use Case

To illustrate the recommended pattern, consider a configuration object that must have a connection string and an API key, and should be immutable after loading:

csharp
public class AppConfig { public required string ConnectionString { get; init; } public required string ApiKey { get; init; } public int TimeoutSeconds { get; init; } = 30; }

This class enforces that both ConnectionString and ApiKey are provided at construction, and they cannot be changed afterward. The TimeoutSeconds property has a default value and is optional. Consumers can create an instance like this:

csharp
var config = new AppConfig { ConnectionString = "Server=...", ApiKey = "abc123" };

If a developer forgets to set ApiKey, the code will not compile. This is the core advantage of combining required and init: the compiler enforces the contract, and the object remains immutable. The pattern scales well to large models and is a recommended approach for modern C# APIs.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.