Can I add an "All" element to the flag enumeration?

If I have an enumeration with several values ​​that may be present at the same time, I create an enumeration of flags:

[Flags] public enum Foo { None = 0, A = 1, B = 2, C = 4, D = 8 } 

If I now want to convey the fact that each value is set, I would need to do something like this:

 Bar bar = new Bar(Foo.A | Foo.B | Foo.C | Foo.D); 

Would it be bad practice / malicious / blasphemy to add an extra All element?

  All = 15 

This will save some space and time when there are many values, and their transfer is a common scenario.

As far as I understand the mechanics of the flags enums (= bitfields), this should work. Are there any side effects that I don't have, or for other reasons, why you shouldn't do this?

+4
source share
4 answers

Can you do this. But maybe you are not using the value 15, but

 All = A | B | C | D 
+8
source

There is a dangerous game here, where if you change All, but the calling components are not recompiled, they will send the old All. If everything is all right with you, than to be.

+2
source

Using bitwise operations is much easier to read.

 [Flags] public enum MyEnum { None = 0, First = 1 << 0, Second = 1 << 1, Third = 1 << 2, Fourth = 1 << 3, All = ~(-1 << 4) } 
+1
source

Most likely, this will be wrong:

 [Flags] public enum Foo { None = 0, A = 1, B = 2, C = 4, D = 8 E = 16 All = 15 } 

Our propeller heads, as a rule, are microfocused, works of E. oh, oh, dear, hell are added ...

And then you take the “Everything” idea one step further and feel the need for AllbutC.

0
source

Source: https://habr.com/ru/post/1414991/


All Articles