Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C#
Tip/Trick

See if a Flags Enum is Valid

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
10 May 2011CPOL 28.1K   2   1
See if an integer value is a valid value for the given "flags" enumerator

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

C#
[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:

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

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

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) Paddedwall Software
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

 
GeneralLeftshifting could fail Pin
leppie11-May-11 1:11
leppie11-May-11 1:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.