Skip to content

Support [NotNullIfNotNull(string)] on indexers #37238

@jcouv

Description

@jcouv

Relates to #35816

See NullableWalker.VisitArguments, which gets the relevant attribute information from ReturnNotNullIfParameterNotNull for method symbols, but we don't have the equivalent for property/indexer symbols.
The NotNullIfNotNull attribute can target a property/indexer.

When we implement this, we should also test the enforcement within the body of the getter.

This also affects extension property scenarios, since these are properties that now have a parameter (the extension parameter) and should also honor this attribute.

    [Fact]
    public void TODO2()
    {
        var src = """
#nullable enable

object? oNull = null;
new C()[oNull].ToString(); // correct warning

object oNotNull = new object();
new C()[oNotNull].ToString(); // should not warn, but does

class C
{
    [property: System.Diagnostics.CodeAnalysis.NotNullIfNotNull(nameof(o))]
    public object? this[object? o] { get => throw null!; }
}
""";
        var comp = CreateCompilation(src, targetFramework: TargetFramework.Net90);
        comp.VerifyEmitDiagnostics(
            // (4,1): warning CS8602: Dereference of a possibly null reference.
            // new C()[oNull].ToString();
            Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new C()[oNull]").WithLocation(4, 1),
            // (7,1): warning CS8602: Dereference of a possibly null reference.
            // new C()[oNotNull].ToString();
            Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new C()[oNotNull]").WithLocation(7, 1));
    }

Note: This issue is referenced in source

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions