The use of properties in .NET relies on the use of backing fields. To reduce the mental load, C# allows use of auto properties and the field
keyword (since C# 14/13-preview). When possible, those auto properties should be applied.
Obviously, this rule should benefit from an additional code-fix.
class NonCompliant
{
public int Prop // Noncompliant {{Use auto property}}
{
get { return m_Prop; }
set { m_Prop = value; }
}
private int m_Prop;
public string WithLogic // Noncompliant {{Use auto field instead of m_WithLogic}}
{
get => m_WithLogic;
set => m_WithLogic = value?.Trim();
}
private string m_WithLogic;
}
class Fixed
{
public int Prop { get; set; }
public string WithLogic
{
get => field;
set => field = value?.Trim();
}
}
class Compliant
{
public string UsingField
{
get => field;
set => field = value?.Trim();
}
public int Prop // Compliant, the backing field has a different type
{
get { return m_Prop ??= Init(); }
}
private int? m_Prop;
private static int Init() => 42;
}