65.9K
CodeProject is changing. Read more.
Home

See if a Flags Enum is Valid

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

May 10, 2011

CPOL
viewsIcon

28582

See if an integer value is a valid value for the given "flags" enumerator

Let's say you have an enumerator defined like so:

[Flags]
public MyFlags { None=0, One=1, Eight=8 };

The following method can be used to see if a given integer value is a valid combination of one or more of the ordinal values:

bool IsFlagsValid(Type enumType, int value)
{
    bool valid = false;
    if (enumType.IsEnum)
    {
        valid = true;
        int maxBit = Convert.ToInt32(Math.Pow(2, Math.Ceiling(Math.Log(value)/Math.Log(2)))) >> 2;
        int i = 1;
        do
        {
            int ordinalValue = (1 << i);
            if (0 != (value & ordinalValue))
            {
                valid = (Enum.IsDefined(enumType, ordinalValue));
                if (!valid)
                {
                    break;
                }
            }
            i++;
        } while (maxBit > i);
    }
    return valid;
} 

Calling the method with any value other than 0, 1, 8, and 9 would return false. For instance, the following would return false:

if (IsFlagsValid(MyFlags, 25))
{
    // do something if the value was valid
}