(From post: .NET 4.0: Enum Base Type )
In .NET 4.0, we’re apparently allowed to freely extend the base type for all enumerations – Enum. This wasn’t previously possible, as the class was regarded static.
As some people might’ve discovered through funny behavior of their programs after switching to .NET 4.0, Enum.HasFlag does NOT return true if the enum value has any of the flags; only if it has ALL of them. The beta of .NET 4.0 didn't act like this, but the release version does.
However, given that we’re now allowed to extend the Enum type, we can simply do the following:
Code:
public static bool HasAnyFlag(this Enum value, Enum toTest)
{
var val = ((IConvertible)value).ToUInt64(null);
var test = ((IConvertible)toTest).ToUInt64(null);
return (val & test) != 0;
}
(Note: There's a valid reason for the UInt64 casts; that is genericness. This method will work on an enum of any base type (Byte, UInt16, UInt32, UInt64, etc).)
This will do what you might’ve originally expected from Enum.HasFlag.
This change appears to be undocumented. At least, I can’t find any MSDN page mentioning that the Enum type can now be used and extended freely.
Of course, with the Enum type now being usable as a variable type, you can extend it much much further than previously possible.
Thanks to Domi for this - he tried compiling a piece of code that extended the Enum type, which turned out to be working, making for this post.