Skip to content

RCS1202 reported when treating a property as an interface type its type implements #1540

@prettybits

Description

@prettybits

Product and Version Used: Roslynator.Analyzers 4.12.6

Steps to Reproduce:
Similarly to the issue reported in #640 for casting this to an interface type it implements, this also happens f.e. when casting a (already null-checked) property to one of its interface types (shown using default interface implementation as that's where I noticed):

public interface I
{
    void M() { }
}

public class P : I;

public class C
{
    public required P Prop { get; set; }

    public void M() 
    {
        if (this.Prop is not null)
        {
            (this.Prop as I).M(); // <--- RCS1202
            ((I)this.Prop).M();
        }
    }
}

Actual Behavior:
warning RCS1202: Avoid NullReferenceException (https://josefpihrt.github.io/docs/roslynator/analyzers/RCS1202)

Expected Behavior:
No warning. Fixing the diagnostic by adding a null check like (this.Prop as I)?.M(); removes the warning, but then SonarAnalyzer.CSharp produces a warning instead as the property has already been checked for null and the as expression isn't considered to possibly be null here: warning S2589: Remove this unnecessary check for null. (https://rules.sonarsource.com/csharp/RSPEC-2589), which I believe to be correct?

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions