check if an enum has any flags in common
You can simply cast the Enum value to a ulong (to account for the possibility that the underlying type is not the default of int). If the result != 0, at least one flag was set.
ulong theValue = (ulong)value;
return (theValue != 0);
Remember, at the end of the day, the enum is backed by one of byte, sbyte, short, ushort, int, uint, long, or ulong.
http://msdn.microsoft.com/en-us/library/sbbt4032.aspx
A flag being set is the same as a corresponding bit being turned on in the backing type. The ulong above will only be 0 if all bits are turned off.
UPDATE
The question was edited after this answer was posted, so here's a modification to account for that update:
To then see whether the enum has any flags in common with another instance of that enum, you can use bitwise and. If both have any common bit position set, the result will be non-zero:
var anyFlagsInCommon = ((ulong)value) & ((ulong)compareTo);
Something like
public static bool HasAnyFlagInCommon(this System.Enum type, Enum value)
{
return (((long)type) & ((long)value)) != 0;
}
The &
gives 1
for any bit that is set in both enums, so if there are any such bits the result is non-zero.
(I've used long
in the hope it will work for whatever type underlies the enum; int
should be fine in your case.)