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;
}