4

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
  • 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. Commented Sep 10, 2018 at 18:07

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.