Frank Puffer
Frank Puffer

Reputation: 8215

C# Enums and Generics

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;
    }
}

Upvotes: 12

Views: 1505

Answers (1)

Tobias Schulte
Tobias Schulte

Reputation: 726

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.

Upvotes: 11

Related Questions