Click here to Skip to main content
15,885,869 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 (3 votes)
11 May 2011CPOL 12.2K   1   3
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.
C#
/// <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;
  }
}

License

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


Written By
Architect
United States United States
Since I've begun my profession as a software developer, I've learned one important fact - change is inevitable. Requirements change, code changes, and life changes.

So..If you're not moving forward, you're moving backwards.

Comments and Discussions

 
GeneralReason for my vote of 5 Elegant and practical solution, well... Pin
DrABELL12-May-11 7:27
DrABELL12-May-11 7:27 
GeneralI agree with your approach. The sad thing is for any given t... Pin
Luc Pattyn11-May-11 15:17
sitebuilderLuc Pattyn11-May-11 15:17 
GeneralRe: Agreed, it should have been supported in some way. As for t... Pin
Andrew Rissing12-May-11 0:37
Andrew Rissing12-May-11 0:37 

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.