From ab07f3a9cb7e2dfb51ce3ec0f072d926ae4400b2 Mon Sep 17 00:00:00 2001 From: Josef Pihrt Date: Fri, 27 Sep 2024 10:25:20 +0200 Subject: [PATCH 1/2] update --- .../AvoidNullReferenceExceptionAnalyzer.cs | 3 ++ ...CS1202AvoidNullReferenceExceptionTests2.cs | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+) 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(); + } + } +} "); } } From 297b3b09350c98d00568941e0406dcb082395b37 Mon Sep 17 00:00:00 2001 From: Josef Pihrt Date: Fri, 27 Sep 2024 10:27:59 +0200 Subject: [PATCH 2/2] update --- ChangeLog.md | 4 ++++ 1 file changed, 4 insertions(+) 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