Fix MA0022 code fix dropping non-null branches and false positive in async methods

Merged
ME
2mo ago
+150-23

What

Two bugs in MA0022 (Return Task.FromResult instead of returning null):

  1. The code fix replaced the whole returned expression, so the non-null branches were lost:

    Task<int> A(bool a) { return a ? null : Task.FromResult(1); }
    

    Expected fix: return a ? Task.FromResult(0) : Task.FromResult(1);. Actual: return Task.FromResult(0);. The same happened with switch expressions, and with a null-conditional access (return x?.A(); became return Task.CompletedTask;, dropping the call).

  2. async methods were not excluded, whereas return null; there completes the task with a null result:

    async Task<Task> A() { await Task.Yield(); return null; }
    

    Expected: no diagnostic. Actual: MA0022.

Fix

  • The fixer walks the returned operation (conversions, ?:, switch expression arms) and replaces only the null constants. The diagnostic location is unchanged (the whole return statement or expression body).
  • When a null value comes from a null-conditional access (?.), there is no syntax node to replace, so the fix is not offered instead of producing a different behavior.
  • The analyzer skips async methods, lambdas, and local functions.
  • docs/Rules/MA0022.md documents both behaviors.

Tests

Added to ReturnTaskFromResultInsteadOfReturningNullAnalyzerTests (all failed before the fix):

  • MethodFixer_ConditionalExpression_OnlyReplacesNull
  • MethodFixer_SwitchExpression_OnlyReplacesNull
  • MethodFixer_ConditionalAccess_NoFix
  • AsyncMethodReturningTaskOfTask_NoDiagnostic (async method, lambda, and local function)

The test class passes on roslyn5.9 (26/26) and roslyn4.8 (26/26).