Is creating a C# generic method that accepts (nullable) value type and reference type possible?

前端 未结 1 1892
情歌与酒
情歌与酒 2020-12-16 16:45

I want to create a simple method that accepts both value type and reference type parameters, i.e. int is value, and string is reference.

So this i

相关标签:
1条回答
  • 2020-12-16 17:29

    Your problem is that you want generic type constraints that are conflicting with each other:

    • Nullable<T> works with value types only
    • Reference types are not value types

    So you will need to have two overloads for your code to work:

    public static bool areBothNotNull<T>(T? p1, T? p2) where T : struct
    {            
        return (p1.HasValue && p2.HasValue);
    }
    
    public static bool areBothNotNull<T>(T p1, T p2)
    {
        return (p1 != null && p2 != null);
    }
    

    Still, the following line will never compile:

    var r3 = areBothNotNull<string>(3, 4);
    

    There is a conflict here, where the generic type argument states that the parameters are of type string, but the code tries to pass ints instead.

    0 讨论(0)
提交回复
热议问题