Skip to content

Commit 9b9cb50

Browse files
Update to check entire block for directives instead of just close brace
This is more conservative and handles cases where directives appear anywhere in the block, not just at the end. Co-authored-by: CyrusNajmabadi <4564579+CyrusNajmabadi@users.noreply.github.com>
1 parent 338ba68 commit 9b9cb50

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/Analyzers/CSharp/Analyzers/UseNullPropagation/CSharpUseNullPropagationDiagnosticAnalyzer.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,13 @@ protected override bool TryAnalyzePatternCondition(
7272
IfStatementSyntax ifStatement,
7373
CancellationToken cancellationToken)
7474
{
75-
// Check if the if-statement has a block statement with directives on the close brace.
75+
// Check if the if-statement has a block statement with preprocessor directives.
7676
// If so, we can't convert to null propagation because the directives (like #if DEBUG)
77-
// would be lost or cause compilation issues.
77+
// would be lost or cause compilation issues. We check the entire block rather than
78+
// just the close brace to handle cases where directives appear anywhere in the block.
7879
if (ifStatement.Statement is BlockSyntax block)
7980
{
80-
if (block.CloseBraceToken.ContainsDirectives)
81+
if (block.ContainsDirectives)
8182
return null;
8283
}
8384

src/Analyzers/CSharp/Tests/UseNullPropagation/UseNullPropagationTests.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2830,6 +2830,29 @@ public void Dispose()
28302830
}
28312831
""");
28322832

2833+
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77777")]
2834+
public Task TestIfStatement_WithPreprocessorDirective_BeforeStatement()
2835+
=> TestMissingInRegularAndScriptAsync(
2836+
"""
2837+
using System.Diagnostics;
2838+
2839+
class C
2840+
{
2841+
private object? _controlToLayout;
2842+
2843+
public void Dispose()
2844+
{
2845+
if (_controlToLayout != null)
2846+
{
2847+
#if DEBUG
2848+
Debug.WriteLine("Debug mode");
2849+
#endif
2850+
_controlToLayout.ToString();
2851+
}
2852+
}
2853+
}
2854+
""");
2855+
28332856
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/77777")]
28342857
public Task TestIfStatement_WithoutPreprocessorDirective_StillWorks()
28352858
=> TestInRegularAndScriptAsync(

0 commit comments

Comments
 (0)