Skip to content

Commit 7789018

Browse files
committed
fix
1 parent 6c761a6 commit 7789018

File tree

2 files changed

+68
-1
lines changed

2 files changed

+68
-1
lines changed

src/Refactorings/CSharp/Refactorings/CheckExpressionForNullRefactoring.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,17 @@ private static async Task<Document> RefactorAsync(
253253
}
254254
}
255255

256-
return await document.InsertNodeAfterAsync(statement, CreateNullCheck(expression), cancellationToken).ConfigureAwait(false);
256+
SyntaxNode nodeInList = statement;
257+
IfStatementSyntax nullCheck = CreateNullCheck(expression);
258+
SyntaxNode newNode = nullCheck;
259+
260+
if (nodeInList.Parent is GlobalStatementSyntax globalStatement)
261+
{
262+
newNode = globalStatement.WithStatement(nullCheck);
263+
nodeInList = globalStatement;
264+
}
265+
266+
return await document.InsertNodeAfterAsync(nodeInList, newNode, cancellationToken).ConfigureAwait(false);
257267
}
258268

259269
private static Task<Document> RefactorAsync(
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
using System.Threading.Tasks;
2+
using Roslynator.Testing.CSharp;
3+
using Xunit;
4+
5+
namespace Roslynator.CSharp.Refactorings.Tests;
6+
7+
public class RR0024CheckExpressionForNullTests : AbstractCSharpRefactoringVerifier
8+
{
9+
public override string RefactoringId { get; } = RefactoringIdentifiers.CheckExpressionForNull;
10+
11+
[Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.CheckParameterForNull)]
12+
public async Task Test()
13+
{
14+
await VerifyRefactoringAsync("""
15+
class C
16+
{
17+
void M()
18+
{
19+
var [|x|] = "".ToString();
20+
}
21+
}
22+
""", """
23+
class C
24+
{
25+
void M()
26+
{
27+
var x = "".ToString();
28+
if (x != null)
29+
{
30+
31+
}
32+
}
33+
}
34+
""", equivalenceKey: EquivalenceKey.Create(RefactoringId));
35+
}
36+
37+
[Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.CheckParameterForNull)]
38+
public async Task Test_TopLevelStatement()
39+
{
40+
await VerifyRefactoringAsync("""
41+
42+
var [|x|] = "".ToString();
43+
var y = x.ToString();
44+
45+
""", """
46+
47+
var x = "".ToString();
48+
49+
if (x != null)
50+
{
51+
52+
}
53+
var y = x.ToString();
54+
55+
""", equivalenceKey: EquivalenceKey.Create(RefactoringId));
56+
}
57+
}

0 commit comments

Comments
 (0)