Skip to content

Commit

Permalink
Convert if-else to return statement when pattern matching is used (do…
Browse files Browse the repository at this point in the history
  • Loading branch information
josefpihrt authored and JochemHarmes committed Oct 30, 2023
1 parent a223081 commit 745921d
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 1 deletion.
1 change: 1 addition & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

-----
<!-- Content below does not adhere to 'Keep a Changelog' format -->
Expand Down
2 changes: 1 addition & 1 deletion src/Common/CSharp/Analysis/If/IfAnalysis.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down

0 comments on commit 745921d

Please sign in to comment.