Considering this:
[Flags]
public enum MyEnum {
One = 1,
Two = 2,
Four = 4,
Eight = 8
}
public static class FlagsHelper
{
public static bool
Unfortunately no there is not a good way to make an extension method like this. In order for this to work you'd need to have a generic method which operated on enum
values. Unfortunately there is no way to constrain generic arguments to be an enum
// Ilegal
public static bool Contains(this T value, T flag) where T : enum {
...
}
The best I've come up with is the following
public static bool HasFlag(this System.Enum e, T flag)
{
var intValue = (int)(object)e;
var intFlag = (int)(object)flag;
return (intValue & intFlag) != 0;
}
However it's limited in several ways
enum
values are int
based. e
is null