Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator '&' cannot be applied to operands of type 'T' and 'T' [duplicate]

My application defines several enums that include the [Flags] attribute.

I wanted to write a small utility method to check if a flag was set for any of those enums and I came up with the following.

protected static bool IsFlagSet<T>(ref T value, ref T flags)
{
    return ((value & flags) == flags);
}

But this gives me the error "Operator '&' cannot be applied to operands of type 'T' and 'T'".

Can this be made to work?

like image 232
Jonathan Wood Avatar asked May 08 '11 18:05

Jonathan Wood


1 Answers

The Enum class already has a utility function: Enum.HasFlag(Flag f), see the example on MSDN

 if (petsInFamily.HasFlag(Pet.Dog))
        familiesWithDog++;

Note: This was introduced in C# 4. And while it's very readable it may have some performance issues.

like image 72
Henk Holterman Avatar answered Oct 04 '22 07:10

Henk Holterman