Click here to Skip to main content
15,884,472 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

See If a Flags Enum is Valid

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
11 May 2011CPOL 5.2K   1  
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.

C#
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.

:)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Belgium Belgium
I am an engineer with a background in electronics, software and mathematics.

I develop technical software, both for embedded systems and for desktop equipment. This includes operating systems, communication software, local networks, image processing, machine control, automation, etc.

I have been using all kinds of microcontrollers and microprocessors (Intel 4004/8080/8051/80386/Pentium, Motorola 680x/680x0/ColdFire/PowerPC, Microchip PIC, Altera NIOS, and many more), lots of programming languages (all relevant assemblers, Fortran, Basic, C, Java, C#, and many more), and different operating systems (both proprietary and commercial).

For desktop applications and general development tools I have been using both UNIX systems and Mac/MacOS for many years, but I have switched to x86-based PCs with Windows, Visual Studio and the .NET Framework several years ago.

I specialize in:
- cross-platform development (making software that runs on diverse hardware/OS combinations)
- instruction set simulation
- improving software performance, i.e. making sure the software runs the job at hand in as short a time as possible on the given hardware. This entails algorithm selection, implementation design, accurate measurements, code optimisation, and sometimes implementing virtual machines, applying SIMD technology (such as MMX/SSE), and more.

Comments and Discussions

 
-- There are no messages in this forum --