diff --git a/src/Meziantou.Analyzer/Rules/AvoidClosureWhenUsingConcurrentDictionaryAnalyzer.cs b/src/Meziantou.Analyzer/Rules/AvoidClosureWhenUsingConcurrentDictionaryAnalyzer.cs index 248a70994..48bdb9aba 100644 --- a/src/Meziantou.Analyzer/Rules/AvoidClosureWhenUsingConcurrentDictionaryAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/AvoidClosureWhenUsingConcurrentDictionaryAnalyzer.cs @@ -184,8 +184,9 @@ private static void DetectClosure(OperationAnalysisContext context, IOperation a var dataFlow = semanticModel.AnalyzeDataFlow(syntax); if (dataFlow.CapturedInside.Length > 0) { + // A parameter can be captured inside (by another lambda) var parameters = GetParameters(argumentOperation); - if (dataFlow.Captured.Any(s => !parameters.Contains(s, SymbolEqualityComparer.Default))) + if (dataFlow.CapturedInside.Any(s => !parameters.Contains(s, SymbolEqualityComparer.Default))) { context.ReportDiagnostic(RuleFactoryArg, argumentOperation, string.Join(", ", dataFlow.Captured.Select(symbol => symbol.Name))); } diff --git a/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzerCommon.cs b/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzerCommon.cs index 84e8839e7..f462f1259 100644 --- a/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzerCommon.cs +++ b/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzerCommon.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis; namespace Meziantou.Analyzer.Rules; diff --git a/tests/Meziantou.Analyzer.Test/Rules/ConcurrentDictionaryMustPreventClosureWhenAccessingTheKeyAnalyzerTests_MA0106.cs b/tests/Meziantou.Analyzer.Test/Rules/ConcurrentDictionaryMustPreventClosureWhenAccessingTheKeyAnalyzerTests_MA0106.cs index a21b0b859..7ca250fe7 100644 --- a/tests/Meziantou.Analyzer.Test/Rules/ConcurrentDictionaryMustPreventClosureWhenAccessingTheKeyAnalyzerTests_MA0106.cs +++ b/tests/Meziantou.Analyzer.Test/Rules/ConcurrentDictionaryMustPreventClosureWhenAccessingTheKeyAnalyzerTests_MA0106.cs @@ -119,4 +119,28 @@ await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } + + [Fact] + public async Task GetOrAdd_NoClosure() + { + const string SourceCode = """ + using System; + using System.Collections.Concurrent; + using System.Linq; + + var dict = new ConcurrentDictionary(); + dict.GetOrAdd("", static layout2 => + { + var types = System.Array.Empty().Where(t => t == layout2); + throw null!; + }); + + var dummy = new object(); + var f = new System.Func(() => dummy != null); + """; + await CreateProjectBuilder() + .WithOutputKind(Microsoft.CodeAnalysis.OutputKind.ConsoleApplication) + .WithSourceCode(SourceCode) + .ValidateAsync(); + } }