This is one that’s irritated me just a little for ages, but never as much as this morning, when I needed to create a whole swag of small-ish flags enums and then test for bits set in them.

Here’s a quick solution:

public static class FlagExtensions
{
    public static bool HasFlag<T>(this T target, T flag) where T: struct
    {
        if (!typeof(T).IsEnum) throw new InvalidOperationException("Only supported for enum types.");

        int targetInt = Convert.ToInt32(target);
        int flagInt = Convert.ToInt32(flag);

        return (targetInt & flagInt) == flagInt;
    }
}

Notably, while we can’t use a where T: Enum constraint in our extension method, an enum (lower-case e) is actually a struct, so we can at least constrain it to structs and then do a quick type-check.

To use it to test whether an enum value has a particular flag set, try this:

MyFlagEnum flags = MyFlagEnum.Default;

if (flags.HasFlag<MyFlagEnum>(MyFlagEnum.Coffee))
{
    // our "Coffee" bit is set. Yum!
}