Fix MA0091 false positive on instance events raised from a static context

Merged
ME
2mo ago
+103-2

What

MA0091 requires the sender of an instance event to be this, even where this is not available:

class Test
{
    public event EventHandler MyEvent;

    static void Raise(Test instance) => instance.MyEvent?.Invoke(instance, EventArgs.Empty);
}
  • Expected: no diagnostic. instance is the correct sender.
  • Actual: MA0091 on instance, and the code fix replaces it with this, which doesn't compile in a static method (CS0026).

The same happens in a static lambda or a static local function.

Fix

  • Added EventsShouldHaveProperArgumentsAnalyzerCommon.CanUseThis, which the analyzer and the fixer share. It returns false in a static member, in a static lambda or static local function, and outside a method (e.g. a field initializer).
  • Analyzer: when this is not available, the sender must be the instance that declares the event, which the analyzer can't reliably identify. So the rule only reports a null sender there. Outside a static context, the behavior is unchanged (the sender must be this). CanUseThis only runs when the sender is not already this.
  • Fixer: the "Use this" fix is not registered when this is not available.
  • Documented the static context behavior in docs/Rules/MA0091.md.

Tests

  • Added ValidSender_InstanceEvent_StaticMethod, ValidSender_InstanceEvent_StaticLambda and InvalidSender_InstanceEvent_StaticMethod_NoCodeFix (a null sender is still reported, but no fix is offered). All 3 failed before the fix.
  • EventsShouldHaveProperArgumentsAnalyzerTests (+ UseEventArgsEmpty filter): 16/16 passed on roslyn5.9 and roslyn4.8.