Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to add an "All" item to a Flags enum?

If I have an enum with multiple values which can be present at the same time, I create a Flags enum:

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

If I now want to pass the fact that every value is set I would have to do something like this:

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

Would it be considered bad practice/harmful/blasphemy to add an additional element All?

    All = 15

This would save some space and time when there are a lot of values and passing them all is a common scenario.

As far as I understand the mechanics of flags enums (=bitfields), this should work. Are there any side effects I am missing or other reasons why you should not do that?

like image 847
magnattic Avatar asked Dec 20 '22 21:12

magnattic


2 Answers

You can do that. But maybe you shoudn't use the value 15, but

All = A | B | C | D
like image 190
Carsten Schütte Avatar answered Dec 23 '22 09:12

Carsten Schütte


There is a dangerous gotcha here where if you change All but the calling components are not recompiled, they will send the old All. If this is fine with you than so be it.

like image 26
Joshua Avatar answered Dec 23 '22 11:12

Joshua