0

In my enum below, my intention is to be able to use Scheduled to mean 'ILT | VILT | HVILT'. In the guidelines for making this kind of enum everyone suggests using powers of 2, obviously, but if I actually mean Scheduled to be a combination of those other values then this should work fine, right?

Or are there any gotchas I should watch out for when doing this?

[Flags]
public enum Modalities
{
    None = 0,
    ILT = 1,
    VILT = 2,
    HVILT = 4,
    Scheduled = 7,
    Online = 8,
    Package = 16,
    All = ~None
}
BVernon
  • 3,205
  • 5
  • 28
  • 64
  • 2
    _"are there any gotchas"_ -- such as? Considering that [the documentation](https://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx) specifically calls this out as a recommended practice -- _"Consider creating an enumerated constant for commonly used flag combinations"_ -- why do you think there would be any problems? I find your question unclear. – Peter Duniho Aug 27 '16 at 07:17
  • 1
    If you do understand that these __will have more than one bit set__, sure, go ahead. So `enum somMode = Modalities.Scheduled; bool ok = somMode.HasFlag(Modalities.ILT)` evaluates to `true`.. – TaW Aug 27 '16 at 07:36
  • @PeterDuniho Haha, I don't think you find my question unclear. I think you just find it unclear how I didn't see that in the documentation. I did in fact look over that page but it appears I scanned it a little too quickly. Thanks for pointing that out to me :) – BVernon Aug 27 '16 at 19:08

1 Answers1

3

As far as functionality is concerned there is nothing to worry about.

When it comes to readability, you might consider two changes.

Firstly, I don't find Scheduled = 7 readable. In this case it is quite simple that it includes ILT, VILT and HVILT flags. But someday you might come across a need to use more complex flags and numbers such as 173 are not so easy to decompose straight away. The proper approach would be to use Scheduled = ILT | VILT | HVILT

Secondly, I don't prefer typing powers of two expliclity. Bitshift operator gives you opportunity to use uniform notation for all enum values.

Here's an example presenting my own thoughts.

[Flags]
public enum Modalities
{
    None = 0,
    ILT = 1 << 0,
    VILT = 1 << 1,
    HVILT = 1 << 2,
    Online = 1 << 3,
    Package = 1 << 4,
    Scheduled = ILT | VILT | HVILT,
    All = ~None
}
bottaio
  • 4,963
  • 3
  • 19
  • 43