Search code examples
c#genericsgeneric-method

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


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?


Solution

  • & is an operator on a class type. Which means that the class T has to have a method that overloads the operator &.

    .Net can't expect that every class will have it. So it fails.

    What you can do, is make a base class, that declares the operator overload as a method.

    Then use Constraints to declare that T uses that base class:

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