diff --git a/ChangeLog.md b/ChangeLog.md index 1f4ee3278f..978246f645 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- Fix analyzer [RCS1202](https://josefpihrt.github.io/docs/roslynator/analyzers/RCS1202) ([PR](https://github.com/dotnet/roslynator/pull/1542)) + ## [4.12.6] - 2024-09-23 ### Added diff --git a/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs b/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs index 59fd512db2..f52f08a171 100644 --- a/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs +++ b/src/Analyzers/CSharp/Analysis/AvoidNullReferenceExceptionAnalyzer.cs @@ -198,6 +198,9 @@ private static void AnalyzeAsExpression(SyntaxNodeAnalysisContext context) if (topExpression is null) return; + if (semanticModel.GetTypeInfo(expression, cancellationToken).Nullability.FlowState == NullableFlowState.NotNull) + return; + if (semanticModel .GetTypeSymbol(asExpression, cancellationToken)? .IsReferenceType != true) diff --git a/src/Tests/Analyzers.Tests/RCS1202AvoidNullReferenceExceptionTests2.cs b/src/Tests/Analyzers.Tests/RCS1202AvoidNullReferenceExceptionTests2.cs index cd9112cf74..2a8f497c64 100644 --- a/src/Tests/Analyzers.Tests/RCS1202AvoidNullReferenceExceptionTests2.cs +++ b/src/Tests/Analyzers.Tests/RCS1202AvoidNullReferenceExceptionTests2.cs @@ -146,6 +146,34 @@ public void M() (this as I).M(); } } +"); + } + + [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AvoidNullReferenceException)] + public async Task TestNoDiagnostic_ExpressionIsDefinitelyNotNull() + { + await VerifyNoDiagnosticAsync(@" +#nullable enable + +public interface I +{ + void M() { } +} + +public class P : I; + +public class C +{ + public required P P { get; set; } + + public void M() + { + if (this.P is not null) + { + (this.P as I).M(); + } + } +} "); } }