Code inspection: Property can be made init-only (private accessibility)
This inspection identifies properties that are only initialized in a constructor and suggests replacing their set
accessor with the init
accessor.
The init
accessor in C# 9.0 and onwards allows properties to be made immutable in a more flexible way than before. Unlike with a readonly
field or get-only property, an init-only property can be set only during object initialization. This helps maintain the immutability of objects after they are created, leading to safer and often simpler code.
public class Blog
{
public Blog(string name)
{
Name = name;
}
public string Name { get; private set; }
}
public class Blog
{
public Blog(string name)
{
Name = name;
}
public string Name { get; private init; }
}
Last modified: 27 May 2024