Fix MA0091 false positive on instance events raised from a static context
Merged
ME
2mo ago+103+103+012345678901234567890123456789-2-2-0123456789
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.
instanceis the correct sender. - Actual: MA0091 on
instance, and the code fix replaces it withthis, 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
thisis not available, the sender must be the instance that declares the event, which the analyzer can't reliably identify. So the rule only reports anullsender there. Outside a static context, the behavior is unchanged (the sender must bethis).CanUseThisonly runs when the sender is not alreadythis. - Fixer: the "Use this" fix is not registered when
thisis not available. - Documented the static context behavior in
docs/Rules/MA0091.md.
Tests
- Added
ValidSender_InstanceEvent_StaticMethod,ValidSender_InstanceEvent_StaticLambdaandInvalidSender_InstanceEvent_StaticMethod_NoCodeFix(a null sender is still reported, but no fix is offered). All 3 failed before the fix. EventsShouldHaveProperArgumentsAnalyzerTests(+UseEventArgsEmptyfilter): 16/16 passed on roslyn5.9 and roslyn4.8.