Why does the compiler reject this code with the following error? (I am using VS 2017
with C# 7.3
enabled.)
CS0019 Operator '==' cannot be applied to operands of type 'T' and 'T'
public class GenericTest<T> where T : Enum
{
public bool Compare(T a, T b)
{
return a == b;
}
}
The version without generics is of course perfectly valid.
public enum A { ONE, TWO, THREE };
public class Test
{
public bool Compare(A a, A b)
{
return a == b;
}
}
The compiler cannot rely on the operator ==
being implemented for every type provided for T
. You could add a constraint to restrict T
to class
, but that would not allow you to use it for your enum, due to the enum not being a reference type. Adding struct
as a constraint would also not allow you to use the operator because structs don't always have an implementation of the ==
operator, but you could use a.Equals(b)
in that case instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With