Cannot apply '&' operator for generic Enum parameters

Viewed 467

I'm trying to write some generic extension methods for flag-style enums. As of C# 7.3, the TFlag type argument can be marked as Enum, but the compiler throws an error for the expression flags & flagToTest, it says that "Operator '&' cannot be applied for type TFlag and TFlag". Since TFlag is an Enum, the '&' operator should work fine.

public static bool IsSet<TFlag>(this TFlag flags, TFlag flagToTest) where TFlag : Enum
{
    if (!Attribute.IsDefined(typeof(TFlag), typeof(FlagsAttribute)))
        throw new InvalidOperationException("The given enum type is not decorated with Flag attribute.");

    if (flagToTest.Equals(0)) 
        throw new ArgumentOutOfRangeException(nameof(flagToTest), "Value must not be 0");

    return (flags & flagToTest) == flagToTest;
}
1 Answers

First of all, take a look at this answer https://stackoverflow.com/a/50219294/6064728. You can write your function in this way or something like this:

public static bool IsSet<TFlag>(this TFlag flags, TFlag flagToTest) where TFlag : Enum
{
    if (!Attribute.IsDefined(typeof(TFlag), typeof(FlagsAttribute)))
        throw new InvalidOperationException("The given enum type is not decorated with Flag attribute.");

    if (flagToTest.Equals(0)) throw new ArgumentOutOfRangeException(nameof(flagToTest), "Value must not be 0");
    int a = Convert.ToInt32(flags);
    int b = Convert.ToInt32(flagToTest);
    return (a & b) == b;
}
Related