dotnet/runtime

NullabilityInfoContext returns incorrect results for an indexer parameter if the class has a property with a value type return type.

Open

#101.071 geöffnet am 15. Apr. 2024

Auf GitHub ansehen
 (2 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)C# (5.445 Forks)batch import
area-System.Reflectionbughelp wanted

Repository-Metriken

Stars
 (17.886 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 12T 11h) (661 gemergte PRs in 30 T)

Beschreibung

Description

If you have a class with: a) a property which returns a value tuple; and b) an indexer with a non-nullable reference type parameter

then when looking at the NullabilityInfoContext for the indexer parameter, it appears as Unknown instead of NotNull.

Reproduction Steps

Create a console app with the following code:

internal class Program
{
    public class Foo
    {
        public string this[string name] => throw new NotImplementedException();

        // *** If you comment out this property, the problem goes away ***
        public (int A, int B) ValueTupleProp { get; }
    }

    static void Main(string[] args)
    {
        // Get the PropertyInfo for the indexer.
        PropertyInfo propInfo = typeof(Foo).GetProperty("Item")!;

        // Get the ParameterInfo for the indexer parameter (non-nullable string).
        ParameterInfo paramInfo = propInfo.GetIndexParameters()[0];

        var nullabilityInfo = new NullabilityInfoContext().Create(paramInfo);

        Console.WriteLine($"{nullabilityInfo.ReadState}, {nullabilityInfo.WriteState}");
        Console.ReadKey();
    }
}

Expected behavior

The NullabilityInfoContext properties report NotNull.

Actual behavior

The NullabilityInfoContext properties report Unknown. However, if you comment out the ValueTupleProp property, then it magically works as expected.

Regression?

No response

Known Workarounds

No response

Configuration

Tried running in .NET 6.0 and .NET 8.0 on Windows 11.

Other information

No response

Contributor Guide