ReSharper 2024.1 Help

Code Inspection: Field can be made readonly (Private Accessibility)

Category

Common Practices and Code Improvements

ID

FieldCanBeMadeReadOnly.Local

EditorConfig

resharper_field_can_be_made_read_only_local_highlighting

Default severity

Suggestion

Language

C#, VB.NET

Requires SWA

No

Say you have decided to make an immutable Person class, initialized only via the constructor. You go ahead and implement the following:

public class Person { private string _name; private int _age; public Person(string name, int age) { _name = name; _age = age; } public override string ToString() => $"Name: {_name}, Age: {_age}"; }
Public Class Person Private _name As String Private _age As Integer Public Sub New(name As String, age As Integer) _name = name _age = age End Sub Public Overrides Function ToString() As String Return String.Format("Name: {0}, Age: {1}", _name, _age) End Function End Class

ReSharper can detect that the fields are only being assigned in the constructor and offers to create an additional safeguard: by marking them readonly, we get to ensure that neither this class nor its users will inadvertently assign new values to these fields.

Last modified: 15 April 2024