How to combine enumerations with flags?

I have an enumeration with flags. I want to declare a variable with n different flags. n > 1 in this case.

 public enum BiomeType { Warm = 1, Hot = 2, Cold = 4, Intermediate = 8, Dry = 16, Moist = 32, Wet = 64, } 

Good - one option is to print each flag in bytes and pass the result to my enumeration.

 BiomeType bType = (BiomeType)((byte)BiomeType.Hot + (byte)BiomeType.Dry) 

But this is a kind of mess - IMHO. Is there a more readable way to combine flags?

+6
source share
3 answers

Simple, use the binary "or" operator :

 BiomeType bType = BiomeType.Hot | BiomeType.Dry; 

In addition, if values ​​can be combined in this way, it is best to mark enum with the Flags attribute to indicate this:

 [Flags] public enum BiomeType { Warm = 1, Hot = 2, Cold = 4, Intermediate = 8, Dry = 16, Moist = 32, Wet = 64, } 

Adding enumeration values ​​is bad for a number of reasons. This makes it easy to create a value that goes beyond certain values, i.e.:

 BiomeType bType = (BiomeType)((byte)BiomeType.Wet + (byte)BiomeType.Wet); 

While far-fetched, this example gives a value of 128, which does not match the known value. It will still compile and run, but most likely you did not create your own code to process values ​​outside the specified ones, and could lead to undefined behavior. However, if you use the pipe operator (or "binary"):

 BiomeType bType = BiomeType.Wet | BiomeType.Wet; 

The result is still BiomeType.Wet .

Also, using an add, as in your question, does not give Intellisense in the IDE, which makes using an enumeration unnecessarily complicated.

+10
source

Add the [Flags] attribute to your listing. Then you can simply mask them:

 [Flags] public enum BiomeType { Warm = 1, Hot = 2, Cold = 4, Intermediate = 8, Dry = 16, Moist = 32, Wet = 64, } BiomeType bType = BiomeType.Hot | BiomeType.Dry; 

(Actually, you can then mask without the flags attribute, but you should add it for clarity.)

You can even do something like this to combine all the flags:

 var allBiomeTypes = ((BiomeType[])Enum.GetValues(typeof(BiomeType))).Aggregate((BiomeType)0, (a, c) => a | c); 
+4
source

Use | (bitwise or) operator . To do this, you get IntelliSense support. (Other bitwise operators work the same as they do on the base numeric type.)

 var bType = BiomeType.Hot | BiomeType.Dry; 

You should also use the [Flags] attribute as a hint for an enum definition:

 [Flags] public enum BiomeType { Warm = 1, Hot = 2, Cold = 4, Intermediate = 8, Dry = 16, Moist = 32, Wet = 64, } 

(For clarification, see What does the [Flags] Enable enumeration attribute in C # mean? )

+3
source

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


All Articles