Code Inspection: Field can be made readonly (Private Accessibility)
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)
{
this.name = name;
this.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)
Me.name = name
Me.age = age
End Sub
Public Overrides Function ToString() As String
Return String.Format("Name: {0}, Age: {1}", name, age)
End Function
End Class
JetBrains Rider can detect that private name
and age
fields are only being assigned in the constructor and offers to create an additional safeguard — by marking them readonly
, we get to ensure that this class will not inadvertently assign these fields anywhere within its methods.
Last modified: 07 April 2022