DEV Community

Nawaf Mahsoun
Nawaf Mahsoun

Posted on

πŸš€ Exploring the Power of init and private set in .NET Development πŸ’ŽπŸ”’

 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;
}
Enter fullscreen mode Exit fullscreen mode

}
`

πŸ’‘ Expert Insight:

Use

init
Enter fullscreen mode Exit fullscreen mode

for values that should never change after creation (Id, CreatedAt).

Use private

Uploading image

set
Enter fullscreen mode Exit fullscreen mode
  • 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! πŸ‘‡

DotNET #CSharp #SoftwareDevelopment #CleanArchitecture #BestPractices #CodingTips

Top comments (0)