C# Init-Only Setters — Complete Guide
In this tutorial, you'll learn about C# Init. We cover key concepts, practical examples, and best practices.
You want an object whose properties cannot change after construction, but using a constructor with ten parameters is unwieldy. Object initializers are clean but require mutable set accessors. Init-only setters give you the best of both.
Wrong
public class Config
{
public string ConnectionString { get; set; } // Can be changed anywhere
public int Timeout { get; set; }
}
var cfg = new Config { ConnectionString = "...", Timeout = 30 };
cfg.Timeout = 60; // Works — but should it?
Output: Properties can be mutated after initialization, breaking immutability guarantees.
Right
public class Config
{
public string ConnectionString { get; init; }
public int Timeout { get; init; }
}
var cfg = new Config { ConnectionString = "...", Timeout = 30 };
// cfg.Timeout = 60; // CS8852: Init-only property can only be assigned in an object initializer
Output: Compiler error CS8852 if you try to mutate after initialization.
The init accessor allows assignment only during object construction — in the constructor, an object initializer, or a with expression.
Prevention
- Use
initinstead ofsetfor properties that should be immutable after creation. - Combine with
requiredmodifier (C# 11) to force callers to provide the value. - Use
initon DTOs, configuration objects, and event arguments. - Use
withexpressions to create modified copies of init-only objects. - Avoid
initon properties that need to change during the object's lifetime.
Common Mistakes with init only setter
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Init-only setters are used in DodaZIP for immutable archive entry metadata. For more C# patterns, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro