Fix MA0056 false positive on members accessed with base

Merged
ME
2mo ago
+31-2

What

MA0056 reported the virtual members accessed with base in a constructor. base calls are not virtual: they always run the base implementation, whatever the runtime type of the instance.

class Base
{
    public virtual void A() { }
    public virtual int P => 0;
    public virtual event System.Action E;
}

class Derived : Base
{
    Derived()
    {
        base.A();    // reported
        _ = base.P;  // reported
        base.E += A; // reported
    }
}

Expected: no diagnostic. Actual: MA0056 on all three lines.

Fix

IsCurrentInstanceMethod now ignores an instance reference whose syntax is a base expression. The operation tree represents both this and base as IInstanceReferenceOperation with ContainingTypeInstance, so the syntax is the only way to tell them apart. This covers invocations, property references and event assignments. The rule documentation mentions the exception.

Tests

Added CtorWithBaseMemberAccess to DoNotCallVirtualMethodInConstructorAnalyzerTests (it failed before the fix). The class passes on roslyn5.9 and roslyn4.8 (15 tests each).