In my .NET journey, Iβve explored the subtle yet impactful world of property setters, where the choice between init and private set can make your domain models safer and your code cleaner. These concepts highlight the balance between immutability and controlled flexibility.
π Understanding the Basics:
init π allows setting a property only during initialization (constructor or object initializer). After that, itβs read-only.
private set **π allows the property to change, but only within the **class, not from outside.
Why does it matter?
Using the right setter pattern prevents accidental mutations and enforces your design intent β crucial for building robust and maintainable applications.
π― Letβs Illustrate with an Example:
`
public class Asset
{
public Guid Id { get; init; }
public DateTime CreatedAt { get; init; }
public string? CreatedBy { get; init; }
public DateTime? UpdatedAt { get; private set; }
public string? UpdatedBy { get; private set; }
public void MarkUpdated(string user)
{
UpdatedAt = DateTime.UtcNow;
UpdatedBy = user;
}
}
`
π‘ Expert Insight:
Use
init
for values that should never change after creation (Id, CreatedAt).
Use private
set
- domain methods for values that evolve (UpdatedAt, Status).
EF Core still works seamlessly with init properties during materialization thanks to reflection.
π€ Share Your Experience:
How do you handle immutability vs flexibility in your .NET domain models? Any tips or patterns that improved your design? Join the conversation below! π
Top comments (0)