Do not report MA0005 for the params array synthesized by a collection expression
Merged
ME
2mo ago+148+148+012345678901234567890123456789-58-58-01234567890123456789
Fixes #1530
What changed
MA0005 (Use Array.Empty<T>()) no longer reports the empty array that the compiler synthesizes for a collection expression.
public static TheoryData<string> Data => ["foo", "bar"]; // MA0005 was reported here
Why
A collection expression calls the collection type's constructor with no arguments, then Add for each element. When that constructor takes a params T[] parameter, as in the TheoryData<T> of the issue, the compiler creates an empty array for it. The user cannot replace that array with Array.Empty<T>(), so the diagnostic was a false positive. MA0005 already skipped these synthesized arrays for method calls, constructor calls and indexers, but not for collection expressions.
Notes for reviewers
- The analyzer now skips any
IArrayCreationOperationwhereIsImplicitis true, since the user did not write that array and cannot replace it. The exception is an array initializer withoutnew(int[] a = { };): Roslyn marks it as implicit, but the user wrote it, so it is still reported. - This replaces
IsCompilerGeneratedParamsArray, which matched the synthesized array against the last argument of the parent method, constructor or indexer call and did not handle collection expressions. The existing tests for those cases and for implicitparamsarrays in attributes still pass. IsInAttributeis kept for an explicitnew int[0]inside an attribute, whereArray.Empty<T>()is not allowed.- Added
CollectionExpression_ParamsConstructor_ShouldNotReportError, which failed before the fix, and tests for array initializers (local and field), an explicit empty array passed toparams, a generic element type, and a non-constant length. TheUseArrayEmptyAnalyzerTestspass on Roslyn 4.8, 4.14, 5.0, 5.6 and 5.9.