65.9K
CodeProject is changing. Read more.
Home

See If a Flags Enum is Valid

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

May 11, 2011

CPOL
viewsIcon

5402

This is an alternative to "See If a Flags Enum is Valid".

This alternative probably is less expensive than Andrew's alternate 1; rather than calculating the maximum value the enum can have, it checks each individual bit that is set in the input value, one by one. There is a hack involved, for any non-zero value the expression value & (-value) yields a number that has exactly one bit set, the lowest one that is also set in value.

public static bool IsFlagsValid<T>(int value) {
    Type enumType = typeof(T);
    while (value!=0) {
        int lowestBit=value & (-value);
        if (!Enum.IsDefined(enumType, lowestBit)) return false;
        value&=~lowestBit;
    }
    return true;
}

There is one limitation: the method's value parameter must have the same type as type T is based on; that is imposed by the IsDefined() method. So one might want to have a second method with long value instead of int value. Maybe, I don't know, this could be remedied by making it even more generic, based on Enum.GetUnderlyingType.

:)