Do not report MA0005 for the params array synthesized by a collection expression

Merged
ME
2mo ago
+148-58

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 IArrayCreationOperation where IsImplicit is true, since the user did not write that array and cannot replace it. The exception is an array initializer without new (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 implicit params arrays in attributes still pass.
  • IsInAttribute is kept for an explicit new int[0] inside an attribute, where Array.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 to params, a generic element type, and a non-constant length. The UseArrayEmptyAnalyzerTests pass on Roslyn 4.8, 4.14, 5.0, 5.6 and 5.9.