Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Go to top

See if a Flags enum is valid

, 11 May 2011
Rate this:
Please Sign up or sign in to vote.
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;
  }
}

License

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

Share

About the Author

Andrew Rissing
Software Developer (Senior)
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... PinmemberDrABELL12-May-11 7:27 
GeneralI agree with your approach. The sad thing is for any given t... PinmvpLuc Pattyn11-May-11 15:17 
GeneralRe: Agreed, it should have been supported in some way. As for t... PinmemberAndrew Rissing12-May-11 0:37 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 11 May 2011
Article Copyright 2011 by Andrew Rissing
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid