0

When I have an enumeration type:

Public Enum EnumerationType
    EnumerationMember1
    EnumerationMember2
    EnumerationMember3
    EnumerationMember4
End Enum

And I want to be able to select more than one member at the time,

s it better to assign a power of 2 as value to each and use bitwise comparison or to use a List?

Orace
  • 7,822
  • 30
  • 45
user4388177
  • 2,433
  • 3
  • 16
  • 30

1 Answers1

4

Indeed you can assign a power of 2 for values. In association with the flag attribute it gives good results.

Particularly when you want to print it using toString. It's C# but you have nice informations here.

The power of 2 solution is really C/C++ oriented and is useful when it comes to be compatible with library written in such languages. It also provides a memory efficient format which is more friendly to database.

If you want to use a collection, a List will have double entries issues, you will prefer to use a HashSet instead. It will gives you facilities to add, remove or find tags in your combined enum without using magic boolean operations.

Also you should ask yourself : does a combined enum makes sense in my case ?

<FlagsAttribute>
Public Enum FileOption
    Readable = 1
    Writable = 2
End Enum

In this case, MyFileOption.Readable Or MyFileOption.Writable makes sense. My file is readable and writable.

In one of my application I control an hardware that can send to the PC streams of data, I can choose which streams I want to be sent.

Public Enum HardwareStreams
    StreamA
    StreamB
    Aux1
    Aux2
End Enum

In this case HardwareStreams.StreamA Or HardwareStreams.Aux1 will not represents a hardware stream. But a set of such enum will makes sense.

Finally it depends on the usage of your enum and it's up to you.

Community
  • 1
  • 1
Orace
  • 7,822
  • 30
  • 45
  • Thank you, I didn't know about the HashSet collection, it is really useful. The FlagsAttribute seems to be useful just when you want to change the ToString() behavior (and maybe for documentation). For the compatibility, the HashSet can be converted to bitwise with a converter, performance-wise I don't think it's going to have a big impact, but all your consideration are really useful. I think, if you don't have special requirements, it's a matter of tastes then. – user4388177 Feb 25 '15 at 15:30
  • @user4388177, Indeed, it's a matter of tastes, if your code will be read by others you also should look at their habits (like company legacy code). Also, can you please consider to accept my answer :o) – Orace Feb 25 '15 at 15:54
  • It's a good answer and I upvoted it, I will just wait few hours to make sure noone has another opinion, then I will accept it. Thanks. – user4388177 Feb 25 '15 at 15:57