Do Not Hide Base Class Methods

ID

csharp.do_not_hide_base_class_methods

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

inheritance, reliability

Description

Reports methods declared with the new modifier in a class that has a base class. The new modifier hides an inherited member with the same name instead of overriding it, which usually produces a confusing two-implementation situation.

Rationale

A new method shadows the base member only when the caller accesses the object through a reference of the derived type. If the same instance is held through a base-class reference, the base implementation runs. Callers cannot guess which one fires without inspecting the static type of every variable, so dispatch becomes accidental and type-dependent rather than polymorphic.

public class BaseLogger
{
    public virtual void Log(string msg) => Console.WriteLine(msg);
}

public class DerivedLogger : BaseLogger
{
    public new void Log(string msg) => Console.Error.WriteLine(msg);   // FLAW
}

public class CorrectLogger : BaseLogger
{
    public override void Log(string msg) => Console.Error.WriteLine(msg); // OK
}

Remediation

If the intent is to substitute behaviour, mark the base method virtual and use override on the derived class instead. If the methods really are unrelated, give the derived method a different name. Reserve new for the rare case where you need to introduce a name that happens to clash with an inherited member but is unrelated.