Skip to content

Commit 5f02670

Browse files
committed
Update SA1003 for null-forgiving operator at end of line when followed by member access
1 parent 9b946ab commit 5f02670

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp8/SpacingRules/SA1003CSharp8UnitTests.cs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,5 +329,39 @@ public void TestMethod(int[] values)
329329

330330
await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false);
331331
}
332+
333+
[Fact]
334+
public async Task TestNullForgivingOperatorAtEndOfLineBeforeMemberAccessAsync()
335+
{
336+
var testCode = @"
337+
namespace TestNamespace
338+
{
339+
public class TestClass
340+
{
341+
public void TestOnParameter(string? maybeNullParameter)
342+
{
343+
var result = maybeNullParameter!
344+
.ToString();
345+
}
346+
347+
private string? _maybeNullProperty;
348+
public void TestOnProperty()
349+
{
350+
var result = _maybeNullProperty!
351+
.ToString();
352+
}
353+
354+
private string? MaybeNullMethod() => null;
355+
public void TestOnMethod()
356+
{
357+
var result = MaybeNullMethod()!
358+
.ToString();
359+
}
360+
}
361+
}
362+
";
363+
364+
await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
365+
}
332366
}
333367
}

StyleCop.Analyzers/StyleCop.Analyzers/SpacingRules/SA1003SymbolsMustBeSpacedCorrectly.cs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -393,9 +393,22 @@ private static void HandlePostfixUnaryExpression(SyntaxNodeAnalysisContext conte
393393
break;
394394
}
395395

396-
// If the next token is a close brace token we are in an anonymous object creation or an initialization.
397-
// Then we allow a new line
398-
bool allowEndOfLine = followingToken.IsKind(SyntaxKind.CloseBraceToken);
396+
bool allowEndOfLine;
397+
if (followingToken.IsKind(SyntaxKind.CloseBraceToken))
398+
{
399+
// If the next token is a close brace token we are in an anonymous object creation or an initialization.
400+
// Then we allow a new line
401+
allowEndOfLine = true;
402+
}
403+
else if (followingToken.IsKind(SyntaxKind.DotToken) && followingToken.IsFirstInLine())
404+
{
405+
// Allow null forgiving operator at end of line when followed by member access on the next line
406+
allowEndOfLine = true;
407+
}
408+
else
409+
{
410+
allowEndOfLine = false;
411+
}
399412

400413
CheckToken(context, unaryExpression.OperatorToken, false, allowEndOfLine, mustHaveTrailingWhitespace);
401414
}

0 commit comments

Comments
 (0)