Search code examples
genericsenumstype-constraintsenum-flagsc#-7.3

Operator '&' cannot be applied to operands of type 'T' and 'T', where T : Enum


I have this enum with Flags attribute

[Flags]
public enum Animal
{
    Null = 0,
    Cat = 1,
    Dog = 2,
    CatAndDog = Cat | Dog
}

And use C# 7.3 which allows type constraints like:

where T : Enum

I create some extension method:

public static bool IsMoreOrEqualThan<T>(this T a, T b) where T : Enum
{
    return (a & b) == b;
}

It returns true if

1) Enum elements are comparable. For example: Animal.Cat and Animal.Dog are not comparable.

AND

2) Element a is more or equal than element b

Examples:

Animal.Cat.IsMoreOrEqualThan(Animal.Null)//true
Animal.Cat.IsMoreOrEqualThan(Animal.Cat)//true
Animal.Cat.IsMoreOrEqualThan(Animal.Dog)//false
Animal.Cat.IsMoreOrEqualThan(Animal.CatAndDog)//false

============================

But i have compillation error: Operator '&' cannot be applied to operands of type 'T' and 'T'

It seems, like .Net developers forgot to allow bitwise operations beetween generic types which has type constraint where T : Enum

Maybe anyone knows the answer?


Solution

  • You can achieve the same result with HasFlag.