C# – Enum with FlagsAttribute or IEnumerable/ISet

cenum

Which is the currently-accepted best practice in terms of C# enum usage, a bitwise [Flags] Enum (compared using | and &) or an IEnumerable of enum values? I'm thinking both from a code-conciseness perspective and from a maintenance perspective.

The only downside to using the Flags approach that I can think of is the inability to enumerate the values without doing the reverse enumeration:

var possibleValues = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();
var applicableValues = possibleValues.Where(x => (containerClass.EnumProperty & x) == x);

Whereas obviously the IEnumerable is easier to query.

EDIT:

As svick rightly pointed out, the IEnumerable would be perhaps the wrong collection to use, an ISet might be a better example.

Best Answer

You can create a method that encapsulates enumerating the flags. This way, using flags is almost as easy as an IEnumerable<T>.

One reason why I would prefer flags is what those two approaches mean. With flags, you have a set. With IEnumerable<T>, you have a sequence. That means you have another edge case you have to consider: What if the sequence contains some item more than once?

Related Topic