Validating a bit flags enum value

This was recently asked in the Code Project Q/A forums, and while there were several responses posted, I think the following is succint and works well.

private static bool IsValidFlagValue<T>(int x) where T : struct
{
    int aggregate = Enum.GetValues(
      typeof(T)).Cast<int>().Aggregate((z, y) => z | y);
    return x <= aggregate && (aggregate & x) > 0;            
}

Note that it does not handle a case where the flag-enum has a 0-value. Here’s a version that does that too (a little less brief).

private static bool IsValidFlagValue<T>(int x) where T : struct
{
    var values = Enum.GetValues(typeof(T)).Cast<int>();
    if (x == 0 && values.Contains(0))
    {
        return true;
    }

    int aggregate = values.Aggregate((z, y) => z | y);
    return x <= aggregate && (aggregate & x) > 0;            
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s