diff --git a/src/Meziantou.Analyzer.CodeFixers/Rules/UsePatternMatchingForNullCheckFixer.cs b/src/Meziantou.Analyzer.CodeFixers/Rules/UsePatternMatchingForNullCheckFixer.cs index f46f0a605..a3ac402f2 100644 --- a/src/Meziantou.Analyzer.CodeFixers/Rules/UsePatternMatchingForNullCheckFixer.cs +++ b/src/Meziantou.Analyzer.CodeFixers/Rules/UsePatternMatchingForNullCheckFixer.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Simplification; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Meziantou.Analyzer.Rules; @@ -51,7 +52,7 @@ private static async Task Update(Document document, BinaryExpressionSy constantExpression = UnaryPattern(constantExpression); } - var newSyntax = IsPatternExpression(expression, constantExpression); + var newSyntax = IsPatternExpression(ParenthesizedExpression(expression).WithAdditionalAnnotations(Simplifier.Annotation), constantExpression); editor.ReplaceNode(node, newSyntax); return editor.GetChangedDocument(); } diff --git a/tests/Meziantou.Analyzer.Test/Rules/UsePatternMatchingForNullCheckAnalyzerTests.cs b/tests/Meziantou.Analyzer.Test/Rules/UsePatternMatchingForNullCheckAnalyzerTests.cs index 7bc282a13..99ae80eb5 100644 --- a/tests/Meziantou.Analyzer.Test/Rules/UsePatternMatchingForNullCheckAnalyzerTests.cs +++ b/tests/Meziantou.Analyzer.Test/Rules/UsePatternMatchingForNullCheckAnalyzerTests.cs @@ -59,6 +59,21 @@ await CreateProjectBuilder() .ShouldFixCodeWith("_ = new object() is not null;") .ValidateAsync(); } + + [Fact] + public async Task NullCheckForObject_FixerKeepParentheses() + { + await CreateProjectBuilder() + .WithSourceCode(""" + string line; + while ([|(line = null) != null|]) { } + """) + .ShouldFixCodeWith(""" + string line; + while ((line = null) is not null) { } + """) + .ValidateAsync(); + } [Fact] public async Task NullEqualsNull()