65.9K
CodeProject is changing. Read more.
Home

See if a Flags enum is valid

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

May 11, 2011

CPOL
viewsIcon

12801

Three improvement ideas:-Add check to ensure the enum is a [Flags] enum.-Make the method generic and static with the enum type generic. I don't know how common it would be to have the type already on hand. It makes it simpler to use.-Iterate over all of the values and bit-wise or them...

Three improvement ideas: -Add check to ensure the enum is a [Flags] enum. -Make the method generic and static with the enum type generic. I don't know how common it would be to have the type already on hand. It makes it simpler to use. -Iterate over all of the values and bit-wise or them together to get a list of only valid bits to use for checking for invalid bits.
/// <summary>
/// Ensures that the provided value is comprised of only valid flags for the provided <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type of the enum to check the flags on.</typeparam>
/// <param name="value">The value to check for only valid flags.</param>
/// <returns>True - the value contains only valid flags; False - otherwise.</returns>
public static bool IsFlagsValid<T>(long value) 
{
  Type enumType = typeof(T);

  if (enumType.IsEnum && enumType.IsDefined(typeof(FlagsAttribute), false))
  {
    long compositeValues = 0;

    // Build up all of the valid bits into one superset.
    foreach (object flag in Enum.GetValues(enumType))
      compositeValues |= Convert.ToInt64(flag);

    // Ensure none of the invalid bits are on.
    return ((~compositeValues & value) == 0);
  }
  else
  {
    return false;
  }
}