Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Fix analyzer [RCS1246](https://josefpihrt.github.io/docs/roslynator/analyzers/RCS1246) ([PR](https://github.com/dotnet/roslynator/pull/1676))
- Fix analyzer [RCS1248](https://josefpihrt.github.io/docs/roslynator/analyzers/RCS1248) ([PR](https://github.com/dotnet/roslynator/pull/1677))
- Fix refactoring [Check expression for null](https://josefpihrt.github.io/docs/roslynator/refactorings/RR0024) ([PR](https://github.com/dotnet/roslynator/pull/1682))

## [4.14.0] - 2025-07-26

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,17 @@ private static async Task<Document> RefactorAsync(
}
}

return await document.InsertNodeAfterAsync(statement, CreateNullCheck(expression), cancellationToken).ConfigureAwait(false);
SyntaxNode nodeInList = statement;
IfStatementSyntax nullCheck = CreateNullCheck(expression);
SyntaxNode newNode = nullCheck;

if (nodeInList.Parent is GlobalStatementSyntax globalStatement)
{
newNode = globalStatement.WithStatement(nullCheck);
nodeInList = globalStatement;
}

return await document.InsertNodeAfterAsync(nodeInList, newNode, cancellationToken).ConfigureAwait(false);
}

private static Task<Document> RefactorAsync(
Expand Down
57 changes: 57 additions & 0 deletions src/Tests/Refactorings.Tests/RR0024CheckExpressionForNullTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System.Threading.Tasks;
using Roslynator.Testing.CSharp;
using Xunit;

namespace Roslynator.CSharp.Refactorings.Tests;

public class RR0024CheckExpressionForNullTests : AbstractCSharpRefactoringVerifier
{
public override string RefactoringId { get; } = RefactoringIdentifiers.CheckExpressionForNull;

[Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.CheckParameterForNull)]
public async Task Test()
{
await VerifyRefactoringAsync("""
class C
{
void M()
{
var [|x|] = "".ToString();
}
}
""", """
class C
{
void M()
{
var x = "".ToString();
if (x != null)
{

}
}
}
""", equivalenceKey: EquivalenceKey.Create(RefactoringId));
}

[Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.CheckParameterForNull)]
public async Task Test_TopLevelStatement()
{
await VerifyRefactoringAsync("""

var [|x|] = "".ToString();
var y = x.ToString();

""", """

var x = "".ToString();

if (x != null)
{

}
var y = x.ToString();

""", equivalenceKey: EquivalenceKey.Create(RefactoringId));
}
}
Loading