So I got really tired of writing the following type of code:
if ((enumValue & MyEnum.Foo) != 0)
{
}
...or even worse, the suggested way of doing this:
if ((enumValue & MyEnum.Foo) == MyEnum.Foo)
{
}
This gets especially tiresome and error prone if you need to check for complex flag combinations. So I thought that maybe an extension method might make it easier, but the best I could come up with so far is:
public static bool HasAnyOf(this Enum thisEnum, Enum flags)
{
return (thisEnum.GetHashCode() & flags.GetHashCode()) != 0;
}
public static bool HasAllOf(this Enum thisEnum, Enum flags)
{
int flagsValue = flags.GetHashCode();
return (thisEnum.GetHashCode() & flagsValue) == flagsValue;
}
Now you can simply write:
if ((enumValue.HasAnyOf(MyEnum.Foo))
{
}
Doesn't seem much easier but as I said when you start needing to check for complex combinations, the code becomes cleaner and easier to follow. But those extension methods have some problems:
- Relying on GetHashCode is a bit of a hack and isn't guaranteed to give the actual value of the enum. Or is it?
- How fast is calling GetHashCode vs casting to a int?
- While the value you passed into the extension method has to be an Enum, there is no type checking to ensure it is the same type of enum as the one that the call is made on.
Any suggestions to improve this?