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
Your problem is that you want generic type constraints that are conflicting with each other:
Nullable<T>
works with value types onlySo 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 int
s instead.