Creating Combination Enum in C#

What is Enum in C#?

Using enum keyword, a set of enumerator list is created. The enumerator list contains constants. The following TextStyles enum has the following constants or enum values.


Typical use of enum

The following example shows that, the textStyle1 has the TextStyles.Heading1 style and the specific actions can be performed using the following switch case.


Create Combinations using Flags Attribute

To make enum combinations, you need to add the Flags attribute to the enum. Then you need to provide values for the enum values. The number should start with 1 and the number (previousValue * 2). The enum value with 0 value is the default value, which cannot be combined with any other values.

The following combination has two enum values such as TextStyles.Bold and TextStyles.Italics


As the TextStyle value is used in the ApplyTextStyle method, the case against the combination could be used as follows.


Combining Combinations

We can also combine combinations. In the following example, we have two combinations styleCombo1 and styleCombo2.

The following method shows that, the above code hits at the combination of TextStyles.Bold, TextStyles.Italics and TextStyles.Underlined. Notice that, TextStyles.Italics is not duplicated if combinations are combined.


Toggling Combination

An enum value can be toggled into a combination. This is achieved using the XOR operation. The following example shows that, the TextStyles.UpperCase is added to styleCombo3.


The following method has the Toggle add scenario where it hits properly.


To toggle the enum value from the combination, you need to do the XOR operation.


Hope this post is useful.

Thanks for reading. Like Method Of Tried in Facebook.