Question

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?

Était-ce utile?

La solution

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

All = A | B | C | D

Autres conseils

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.

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)
}

The most likely place this will go wrong is

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

Us propeller heads tend to be microfocused, added E job done. oops, oh dear, damn....

And then you take the All idea one step further and feel a need for AllbutC.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top