C# init vs set: Choosing the Right Property Accessor
Understand the difference between C# init and set accessors, when to use each, and how init supports immutable objects with object initializers.

When you create a C# class, choosing between init and set controls when a property can be assigned. The init accessor, introduced in C# 9, limits assignment to object initialization; set allows assignment at any time after the object is created. This distinction directly affects how you design immutable objects and enforce data integrity.
Consider a simple Product class. With a traditional set accessor, you can modify properties anytime:
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}This allows code to create a product and later change its Name or Price, which may be desirable for mutable entities. However, for value objects or DTOs where values should not change after creation, set introduces accidental modification risks.
The init accessor restricts assignment to the initialization phase:
public class Product
{
public string Name { get; init; }
public decimal Price { get; init; }
}With init, you can still use object initializers:
var product = new Product
{
Name = "Coffee Maker",
Price = 49.99m
};But after product is constructed, any attempt to assign product.Name produces a compile-time error. This enforces immutability without requiring a constructor with many parameters.
How Object Initializers Interact with init and set
Object initializers are a common way to construct objects concisely. They work with both init and set, but they behave differently regarding the object's lifecycle. With set, you can assign properties in the initializer and later reassign them. With init, the initializer is the last place an assignment is allowed.
The C# compiler treats init accessors specially: outside the supported initialization contexts, they cannot be called by ordinary code after construction. The following code fails to compile:
var product = new Product { Name = "Espresso Machine" };
product.Name = "Drip Filter"; // Error CS8852: init-only property can only be assigned during initializationThis compile-time enforcement prevents accidental modifications and makes the intent clear to other developers.
When to Use init Over set
The decision between init and set hinges on whether you need mutability after construction. Use init when:
- The property represents a value that logically belongs to the object's identity.
- You want to enable object initializers without exposing setters.
- You need to create immutable records or DTOs.
- You want to support
withexpressions to create modified copies.
Use set when:
- The property must be updated frequently (e.g., a status field).
- The object is an entity that changes over time.
- You are implementing a class that requires setters for data binding or serialization.
For example, a Customer entity with an Email that can change over time should use set. A Coordinates class representing a point should use init to keep the values fixed.
Defining init-Only Properties and Constructors
You can also assign init-only properties from within a constructor. This is useful when you want to validate parameters before assignment:
public class Product
{
public string Name { get; init; }
public decimal Price { get; init; }
public Product(string name, decimal price)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Name is required.", nameof(name));
if (price < 0)
throw new ArgumentOutOfRangeException(nameof(price), "Price cannot be negative.");
Name = name;
Price = price;
}
}In this case, the constructor sets the properties, and because they are init, they cannot be changed later. This pattern ensures that validation logic is centralized and invariants are maintained.
Unlike a set accessor, an init accessor can be used in a constructor, but not in arbitrary methods of the class. This means you cannot write a method that modifies the property, which is exactly the enforceability you want for immutable types.
Compatibility and Older C# Versions
init accessors are a C# 9 feature. They require a compiler that supports C# 9 and, on older target frameworks such as .NET Core 3.1 or .NET Framework, the IsExternalInit type that init-only setters rely on. If that support is not available, you cannot use init directly; use set or constructor-only properties instead.
Even with private setters, you can approximate immutability but lose the ability to use object initializers. A common workaround is to define a constructor and expose properties with { get; } only, but that forces you to list all parameters in the constructor, which becomes awkward for many properties.
For modern .NET projects, init is a straightforward way to achieve immutability without sacrificing object initializer syntax.
Comparing init, set, and Get-Only Properties
To clarify the differences, consider the following class:
public class Example
{
public string ReadWrite { get; set; }
public string ReadOnly { get; }
public string InitOnly { get; init; }
public Example(string readOnly)
{
ReadOnly = readOnly;
}
}ReadWritecan be assigned at any time.ReadOnlycan be assigned only in the constructor.InitOnlycan be assigned in the constructor or object initializer, but not after construction.
The following table summarizes the assignment capabilities:
| Accessor | Constructor | Object Initializer | After Construction |
|---|---|---|---|
set | Yes | Yes | Yes |
init | Yes | Yes | No |
get only | Yes | No | No |
How init Works with with Expressions and Records
init accessors make it convenient to use with expressions with records without exposing public setters. Positional records, introduced in C# 9, use init-only properties by default to provide value equality and copy semantics while keeping properties read-only after construction.
public record Product(string Name, decimal Price);
var original = new Product("Coffee Maker", 49.99m);
var updated = original with { Price = 59.99m };The with expression creates a copy of original, applies the specified property changes, and returns a new Product instance. with expressions do not require every record property to be init-only; mutable record properties can also be used with them. But init-only properties are a good fit because they keep the copied instance read-only after the update.
If you prefer a class over a record but still want immutable updates, you can manually implement a With method that returns a new instance, using init-only properties to assign the modified values:
public class Product
{
public string Name { get; init; }
public decimal Price { get; init; }
public Product With(string? name = null, decimal? price = null)
{
return new Product
{
Name = name ?? Name,
Price = price ?? Price
};
}
}This pattern is most useful when you want to preserve the class semantics while gaining immutable updates.
Potential Pitfalls and How to Avoid Them
One common mistake is using init on collections. If you expose a mutable collection like List<T> through an init-only property, the property reference cannot be reassigned, but the collection's contents can still be changed. To prevent callers from modifying the collection through the property, expose a read-only interface such as IReadOnlyCollection<T> or IReadOnlyList<T>, or use an immutable collection type.
Another pitfall is serialization frameworks that rely on setters. Some serializers expect a writable setter to populate properties during deserialization. Verify that your serializer supports init-only properties before adopting init in a DTO layer; if it does not, you may need a newer version or a different deserialization strategy.
Additionally, mixing init and set accessors in the same class can lead to confusion. If you have a class with some mutable and some immutable properties, document the intent clearly. A better approach is to separate concerns into distinct types: one immutable value object and one mutable entity wrapper.
Performance and Memory Considerations
The difference between init and set is negligible at runtime. The init accessor is a compile-time feature; the generated setter is marked as init-only so the compiler can enforce the assignment rules. There is no additional memory overhead or runtime cost compared with a normal set accessor. The primary benefit is immutability, which makes your code safer in multi-threaded scenarios by reducing the need for defensive copies.
When you use with expressions, you allocate a new object, which has a minor cost. If you are performing thousands of such operations per second, measure the impact, but in typical application code, the overhead is negligible. The safety gains from immutable objects usually outweigh the cost.
Making the Right Choice for Your C# Code
The decision between init and set is a design choice that affects the API surface of your types. Use init by default for properties that represent values that should not change after creation. Use set only when mutability is a requirement. This approach leads to more predictable code and fewer bugs.
For modern C# codebases, adopting init for value-like types is a straightforward way to enforce immutability. For older runtimes without the necessary C# 9 support, you can still use private setters for a similar effect, but you lose object initializer convenience.
Consider a User class. If Username and Email are immutable identifiers, use init. If LastLoginAt changes frequently, use set. By applying this rule consistently, you create a clear contract for how each property can be modified, making the code easier to reason about and maintain.
Ultimately, choosing between init and set is not about which syntax is better; it is about matching the accessor to the intended lifecycle of each property.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.