dotnet / roslyn-analyzers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CA2263 shouldn't trigger for overloads with unsatisfied `notnull` generic constrain

MaceWindu opened this issue · comments

Analyzer

Diagnostic ID: CA2263: Prefer generic overload when type is known

Analyzer source

NuGet Package: Microsoft.CodeAnalysis.NetAnalyzers

Version: 9.0.0-preview.24122.1

Describe the bug

CA2263 propose to use generic overload for type, that doesn't satisfy overload's notnull generic type

Steps To Reproduce

public static class TestClass
{
    public static T? Test1<T>(ITest1 tester)
    {
        // bad suggestion
        return (T?)tester.Test(typeof(T));

        // CS8714: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'ITest.Test<T>()'.Nullability of type argument 'T' doesn't match 'notnull' constraint.
        //return tester.Test<T>();
    }

    public static T? Test2<T>(ITest1 tester)
        where T : notnull
    {
        // good suggestion
        //return (T?)tester.Test(typeof(T));

        return tester.Test<T>();
    }

    public static T? Test3<T>(ITest2 tester)
    {
        // good, no suggestion
        return (T?)tester.Test(typeof(T));

        //return tester.Test<T>();
    }

    public static T? Test4<T>(ITest2 tester)
        where T : Enum
    {
        // good suggestion
        //return (T?)tester.Test(typeof(T));

        return tester.Test<T>();
    }
}

public interface ITest1
{
    T? Test<T>() where T : notnull;

    object? Test(Type type);
}

public interface ITest2
{
    T? Test<T>() where T : Enum;

    object? Test(Type type);
}

Expected behavior

No errors when generic constrain not satisfied

Actual behavior

Proposed code change trigger compilation error