Member Initializer Ignored

ID

csharp.member_initializer_ignored

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

dead_code, reliability

Description

Reports field declarators with an inline initializer that is overwritten by every constructor of the enclosing type. The initial value runs once during construction and is then unconditionally replaced, making the initializer dead code.

Rationale

Inline field initializers are convenient for "always this default" cases. If every constructor unconditionally assigns the field, the initializer never reaches any caller, so it is misleading at best and a code-review hazard at worst (a reader may assume the default holds even when no constructor is invoked, which is impossible for instance fields). The fix is either to remove the initializer or to drop the redundant assignments.

public class Order
{
    private int _quantity = 42;                             // FLAW

    public Order()
    {
        _quantity = 0;
    }

    public Order(int q)
    {
        _quantity = q;
    }
}

public class OrderOk
{
    private int _quantity = 42;                             // OK - kept; ctor leaves it

    public OrderOk(int q)
    {
        if (q > 0)
        {
            _quantity = q;
        }
    }
}

public class Defaulted
{
    private int _quantity = 42;                             // OK - no constructor declared
}

Remediation

Either remove the inline initializer (every constructor sets the field anyway) or drop the redundant constructor assignments and rely on the inline default. Pick whichever expresses the intent more clearly.