Skip to content

NullabilityInfoContext returns incorrect result when code analysis attributes are used in a disabled context #63848

@madelson

Description

@madelson

Description

Attributes like DisallowNull and MaybeNull are still respected by the compiler even when the code they are annotating is otherwise nullable-oblivious. NullabilityInfoContext should do the same.

Reproduction Steps

public void Main()
{
        var context = new NullabilityInfoContext();
        
        var disallowNullInfo = context.Create(typeof(DisabledWithCodeAnalysisAttributes).GetProperty("DisallowNull")!);
        Console.WriteLine(disallowNullInfo.ReadState); // Unknown
        Console.WriteLine(disallowNullInfo.WriteState); // Unknown (should be NotNull)

        var maybeNullInfo = context.Create(typeof(DisabledWithCodeAnalysisAttributes).GetProperty("MaybeNull")!);
        Console.WriteLine(maybeNullInfo.ReadState); // Unknown (should be Nullable)
        Console.WriteLine(maybeNullInfo.WriteState); // Unknown
}

#nullable disable
    private class DisabledWithCodeAnalysisAttributes
    {
        [DisallowNull] public string DisallowNull { get; set; }
        [MaybeNull] public string MaybeNull { get; set; }
    }
#nullable enable

Expected behavior

The property DisallowNull should have a NotNull write state because the following produces a compiler warning (CS8625):

new DisabledWithCodeAnalysisAttributes().DisallowNull = null;

The property MaybeNull should have a Nullable read state because the following produces a compiler warning (CS8600):

string s = new DisabledWithCodeAnalysisAttributes().MaybeNull;

Actual behavior

All states are Unknown.

Regression?

No response

Known Workarounds

No response

Configuration

VS 17.0.2, .NET 6, Windows 10 x64.

I don't have any reason to believe this is configuration specific.

Other information

CC @Shane32

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions