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.
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
}
}
class MyClass
{
private int field = 1;
private int Property { get; set; } = 42;
public void Print()
{
field++;
Console.WriteLine(field);
Console.WriteLine(Property);
}
}
System.SerializableAttribute attribute.set or init accessor, declared inside a private nested type. Since no code
outside the enclosing type can reach such a type, a public accessor 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;
}
}