Fix MA0022 code fix dropping non-null branches and false positive in async methods
Merged
ME
2mo ago+150+150+012345678901234567890123456789-23-23-01234567890123456789
What
Two bugs in MA0022 (Return Task.FromResult instead of returning null):
-
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 withswitchexpressions, and with a null-conditional access (return x?.A();becamereturn Task.CompletedTask;, dropping the call). -
asyncmethods were not excluded, whereasreturn null;there completes the task with anullresult:async Task<Task> A() { await Task.Yield(); return null; }Expected: no diagnostic. Actual: MA0022.
Fix
- The fixer walks the returned operation (conversions,
?:,switchexpression arms) and replaces only the null constants. The diagnostic location is unchanged (the wholereturnstatement 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.mddocuments both behaviors.
Tests
Added to ReturnTaskFromResultInsteadOfReturningNullAnalyzerTests (all failed before the fix):
MethodFixer_ConditionalExpression_OnlyReplacesNullMethodFixer_SwitchExpression_OnlyReplacesNullMethodFixer_ConditionalAccess_NoFixAsyncMethodReturningTaskOfTask_NoDiagnostic(async method, lambda, and local function)
The test class passes on roslyn5.9 (26/26) and roslyn4.8 (26/26).