3

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;
}
maccettura
  • 10,514
  • 3
  • 28
  • 35
Gabor
  • 45
  • 4
  • 1
    I think there is a 'HasFlag' method on the instance of the enum that you can call which provide this functionality. They do require the 'Flags' attribute just as your code checks for. – C Smith Sep 10 '18 at 18:07

1 Answers1

1

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;
}
Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46