Click here to Skip to main content
Click here to Skip to main content

Tagged as

See if a Flags enum is valid

, 16 May 2011 CPOL
// A faster solutionreturn (value & mask) == 0;// Where mask == ~ (None | One | Eight)// This constant can be precomputed at compile-time or run-time (like in Alternate 1)

Alternatives

Members may post updates or alternatives to this current article in order to show different approaches or add new features.

10 May 2011
John Simmons / outlaw programmer
6 alternatives  
See if an integer value is a valid value for the given "flags" enumerator
11 May 2011
Andrew Rissing
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...
11 May 2011
Luc Pattyn
This alternative probably is less expensive than Andrew's alternate 1; rather than calculating the maximum value the enum can have, it checks each individual bit that is set in the input value, one by one. There is a hack involved, for any non-zero value the expression value & (-value) yields a...
7 Jul 2011
John Simmons / outlaw programmer
.Net 4 has the enum.HasFlag() method, which kinda obsoletes this tip. :)
17 May 2011
FDW
What about a more complete approach?Define a few caches:private static GenericAlias.Dictionary aoCompositeValues = new GenericAlias.Dictionary();private static GenericAlias.Dictionary aoArrayOfValues = new GenericAlias.Dictionary<Type,...
17 May 2011
Richard Deeming
You can use System.Linq.Expressions to avoid converting the Enum value to an integer type.Here's a solution inspired by the MiscUtil project[^]:using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions; public static class...

License

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

Share

About the Author

YvesDaoust
CEO VISION fOr VISION
Belgium Belgium
I fell into applied algorithmics at the age of 16 or so. This eventually brought me to develop machine vision software as a professional. This is Dreamland for algorithm lovers.

| | Privacy | Terms of Use | Mobile
Web01 | 2.8.150301.1 | Last Updated 17 May 2011
Article Copyright 2011 by YvesDaoust
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid