diff --git a/ChangeLog.md b/ChangeLog.md index ac26e49dc2..174e085daf 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -33,6 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Do not suggest to make local variable a const when it is used in ref extension method ([RCS1118](https://github.com/JosefPihrt/Roslynator/blob/main/docs/analyzers/RCS1118.md)) ([#948](https://github.com/josefpihrt/roslynator/pull/948). - Fix formatting of argument list ([#952](https://github.com/josefpihrt/roslynator/pull/952). - Do not remove async/await when 'using declaration' is used ([#953](https://github.com/josefpihrt/roslynator/pull/953). +- Convert if-else to return statement when pattern matching is used ([RCS1073](https://github.com/JosefPihrt/Roslynator/blob/main/docs/analyzers/RCS1073.md)) ([#956](https://github.com/josefpihrt/roslynator/pull/956). ----- diff --git a/src/Common/CSharp/Analysis/If/IfAnalysis.cs b/src/Common/CSharp/Analysis/If/IfAnalysis.cs index 319b785213..f8ebb91991 100644 --- a/src/Common/CSharp/Analysis/If/IfAnalysis.cs +++ b/src/Common/CSharp/Analysis/If/IfAnalysis.cs @@ -219,7 +219,7 @@ private static IfAnalysis CreateIfToReturnStatement( SemanticModel semanticModel, CancellationToken cancellationToken) { - if ((nullCheck.Style & NullCheckStyles.ComparisonToNull) != 0 + if ((nullCheck.Style & (NullCheckStyles.ComparisonToNull | NullCheckStyles.IsPattern)) != 0 && AreEquivalent(nullCheck.Expression, expression1)) { return CreateIfToReturnStatement(isNullable: false); diff --git a/src/Tests/Analyzers.Tests/RCS1073ConvertIfToReturnStatementTests.cs b/src/Tests/Analyzers.Tests/RCS1073ConvertIfToReturnStatementTests.cs index b8fd95b743..10859f2bc0 100644 --- a/src/Tests/Analyzers.Tests/RCS1073ConvertIfToReturnStatementTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1073ConvertIfToReturnStatementTests.cs @@ -76,6 +76,72 @@ bool M() "); } + [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.ConvertIfToReturnStatement)] + public async Task Test_IfReturn_EqualsToNull() + { + await VerifyDiagnosticAndFixAsync(@" +class C +{ + string M() + { + string x = null; + + [|if (x == null) + { + return null; + } + else + { + return x; + }|] + } +} +", @" +class C +{ + string M() + { + string x = null; + + return x; + } +} +"); + } + + [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.ConvertIfToReturnStatement)] + public async Task Test_IfReturn_IsNull() + { + await VerifyDiagnosticAndFixAsync(@" +class C +{ + string M() + { + string x = null; + + [|if (x is null) + { + return null; + } + else + { + return x; + }|] + } +} +", @" +class C +{ + string M() + { + string x = null; + + return x; + } +} +"); + } + [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.ConvertIfToReturnStatement)] public async Task TestNoDiagnostic_IfElseContainsComment() {