Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CA1861 false positive in method attribute #7033

Closed
koenigst opened this issue Nov 15, 2023 · 2 comments · Fixed by #7044
Closed

CA1861 false positive in method attribute #7033

koenigst opened this issue Nov 15, 2023 · 2 comments · Fixed by #7044

Comments

@koenigst
Copy link

Analyzer

Diagnostic ID: CA1861: Avoid constant arrays as arguments

Analyzer source

Version: SDK 8.0.100

Describe the bug

A constant array in an attribute initializer produces diagnostic CA1861 but extracting the array into a static field is not possible due to language constraints.

Steps To Reproduce

  1. Enable all analyzers.
    <EnableNETAnalyzers>true</EnableNETAnalyzers>
    <AnalysisMode>All</AnalysisMode>
  1. Add attribute with array.
public class Test
{
    [Xunit.Theory]
    [Xunit.InlineData("a", new[] { "b" })]
    public void Method(string a, string[] b) { }
}

Expected Behavior:
The array new[] { "b" } has no compiler warnings.

Actual Behavior:
The array new[] { "b" } has a CA1861 warning but the code cannot be changed because no field is allowed in attribute syntax.

@JeppeSN
Copy link

JeppeSN commented Nov 16, 2023

Happens for other attributes, like NUnit.Framework.TestCaseAttribute where it would be:

[TestCase("a", new[] { "b" })]   // false CA1861

A hillarious workaround is to write:

[Xunit.InlineData("a", (string[])["b"])]

where the cast (string[]) is needed only if the attribute class constructor in question takes a very general argument, like object. If the receiver already wants a concrete array, ["b"] without cast is sufficient.

@DoctorKrolic
Copy link
Contributor

@mavasani How roslyn analyzers are updated for users? Are they bound to version of VS or .NET SDK or what? This issue if fixed sor quite some time, but I still have this bug (VS 17.9P5, latest .NET 8 SDK). Very annoying...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants