- What is happening when we trying to compare two generic type variables?
- How to make possible comparing reference types?
- Why we can’t compare two value type variables?
We can’t compare two generics type variables because the C# compiler knows nothing about specified types. We can make possible comparing reference types using the class constrain. However we can’t compare two value types because the C# compiler knows nothing about comparing value types. The C# compiler can emit code which compares primitive types but we can constrain generics method only with interfaces, non-sealed classes and other type parameters.
Example 1:
//Operator ‘==’ cannot be applied to operands of type ‘T’ and ‘T’
private static void ComparingTwoGenericStructTypeVariables<T>(T o1, T o2) where T : struct
{
if (o1 == o2) { } // Error
}
Example 2:
//’int’ is not a valid constraint. A type used as a constraint must be an interface,
//a non-sealed class or a type parameter.
private static void ComparingTwoGenericTypeVariables<T>(T o1, T o2) where T : int
{
if (o1 == o2) { } // Error
}