From e9488081d37ed4e3b4188e0ebab4efa99c0a681f Mon Sep 17 00:00:00 2001 From: Thomas Shephard Date: Sat, 14 Dec 2024 11:06:53 +0000 Subject: [PATCH] fix: CA1859 false positive on anonymous types --- .../Performance/UseConcreteTypeAnalyzer.cs | 6 ++++++ .../Performance/UseConcreteTypeTests.cs | 16 ++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseConcreteTypeAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseConcreteTypeAnalyzer.cs index 8fc621bf3e..1e23b19f9f 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseConcreteTypeAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseConcreteTypeAnalyzer.cs @@ -324,6 +324,12 @@ void Evaluate(ISymbol affectedSymbol, ITypeSymbol fromType, PooledConcurrentSet< } } + if (toType.IsAnonymousType) + { + // don't recommend upgrading to an anonymous (i.e. invalid) type + return; + } + if (toType.TypeKind is not TypeKind.Class and not TypeKind.Array and not TypeKind.Struct) { // we only deal with classes, arrays, or structs diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/UseConcreteTypeTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/UseConcreteTypeTests.cs index 5e15e69340..e8ea0a14ef 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/UseConcreteTypeTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/UseConcreteTypeTests.cs @@ -1502,6 +1502,22 @@ private void M(ValueTuple vt) await TestCSAsync(Source); } + [Fact, WorkItem(7504, "https://github.com/dotnet/roslyn-analyzers/issues/7504")] + public static async Task ShouldNotSuggestChangingToAnonymousType() + { + const string Source = @" + class Foo + { + object Bar() + { + var outputData = new { A = 1, B = 2 }; + return outputData; + } + }"; + + await TestCSAsync(Source); + } + private static async Task TestCSAsync(string source, params DiagnosticResult[] diagnosticResults) { var test = new VerifyCS.Test