Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Enums and Generics

Tags:

c#

enums

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;
    }
}
like image 458
Frank Puffer Avatar asked Aug 02 '19 07:08

Frank Puffer


1 Answers

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.

like image 94
Tobias Schulte Avatar answered Nov 05 '22 15:11

Tobias Schulte