Code inspection: Property can be made init-only (non-private accessibility)
Category: Common Practices and Code Improvements
ID: PropertyCanBeMadeInitOnly.Global
EditorConfig: resharper_property_can_be_made_init_only_global_highlighting=[error|warning|suggestion|hint|none]
Language: C#, VB.NET
Requires SWA: Yes
tip
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.
Suboptimal code
public class Blog{ public Blog(string name) { Name = name; } public string Name { get; set; }}
After the quick-fix
public class Blog{ public Blog(string name) { Name = name; } public string Name { get; init; }}
For the solution-wide inspection to work, you need to enable at least one of the following:
Simplified global usage checking: select Show unused non-private type members when solution-wide analysis is off on the Editor | Inspection Settings page of JetBrains Rider settings .
Solution-wide analysis: select Enable solution-wide analysis on the Editor | Inspection Settings page of JetBrains Rider settings .
Note that even if the reported accessor has no direct usages in your solution, there could be cases where it is used indirectly — for example, via reflection — or it could just be designed as public API. In all those cases, you would want to suppress the usage-checking inspection for the accessor in one of the following ways:
The recommended way is to decorate the implicitly used accessor with a code annotation attribute. There are two attributes for this purpose: [UsedImplicitly] and [PublicAPI], which are functionally similar, but let you and your teammates understand how the accessor is actually used.
You can also suppress usage-checking inspections with any custom attribute. To do so, mark the definition of that attribute with the [MeansImplicitUse] attribute.
And finally, you can suppress a specific usage-checking inspection as any other code inspection with a suppression comment or a suppression attribute.