2

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?

2 Answers2

0

I change my method this way

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

and now It works

0

You can achieve the same result with HasFlag.

Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59