Why is this an issue?
Fields and auto-properties that are never assigned to hold the default values for their types. They are either pointless code or, more likely, mistakes.
Noncompliant code example
class MyClass
{
private int field; // Noncompliant, shouldn't it be initialized? This way the value is always default(int), 0.
private int Property { get; set; } // Noncompliant
public void Print()
{
Console.WriteLine(field); //Will always print 0
Console.WriteLine(Property); //Will always print 0
}
}
Compliant solution
class MyClass
{
private int field = 1;
private int Property { get; set; } = 42;
public void Print()
{
field++;
Console.WriteLine(field);
Console.WriteLine(Property);
}
}
Exceptions
- Fields on types decorated with
System.SerializableAttributeattribute. - Non-static auto-properties with a public
setorinitaccessor, declared inside a private nested type. Since no code outside the enclosing type can reach such a type, apublicaccessor signals that the property is meant to be populated by reflection-based code. Fields, static properties, get-only properties, and properties with a non-public setter are still reported.public class ConfigurationLoader { public string LoadName(string json) => JsonSerializer.Deserialize<Settings>(json).Name; private class Settings { public string Name { get; set; } // Compliant: a serializer or model binder can set this property public string DisplayName => Name; } }