page 1 of 1
Comments: 3 | Views: 168

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:

  1. Relying on GetHashCode is a bit of a hack and isn't guaranteed to give the actual value of the enum. Or is it?
  2. How fast is calling GetHashCode vs casting to a int?
  3. 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?

1. That's not a bit of a hack. That's a monster hack.

2. See 1 Big Smile

3. You can do something like

     if (thisEnum.GetType() != flags.GetType()) throw ...;

 

Suggestions:

  •  Well, instead of GetHashCode you can simply use Convert.ToInt32 (or Convert.ToInt64 if you want to be 100% on the safe side).
  • The Enum type is a class which means that the enum value will likely get boxed when your methods are called. Not the most efficient way to do things.

I'd rather create extension methods for specific enums rather than trying to do this. It's not like there are a billion enums (with "flags" behavior) in a given code base.

page 1 of 1
Comments: 3 | Views: 168
Microsoft Communities