Combinable enums in .net

As well as creating normal enums we can create combined enum values. To do this decorate the enum with a Flags attribute this allows the string to output the combination of names.We also need to provide specific values for each member and we do this power of two for example 0,1,2,4,8.


public enum Sides
public class EnumCombinationsDemo
public static void Test()
var leftRightCombination = Sides.Left | Sides.Right;//Output : Left | Right
var topBottomCombination = Sides.Top | Sides.Bottom;//Output : Top | Bottom
bool isTopIncluded = topBottomCombination.HasFlag(Sides.Top); //Output : true
//Combining combinations
var allCombinations = leftRightCombination | topBottomCombination; //Output : Left | Right | Top | Bottom
//toggling values
allCombinations ^= Sides.Top; //Output : Left | Right | Bottom
allCombinations ^= Sides.Top; //Output : Left | Right | Top | Bottom

Enjoy coding…

2 thoughts on “Combinable enums in .net

  1. It is not simply ‘power of two for example 0,1,2,4,8’ .The reason is we are giving a bit position to each enum value and OR ing the values to get new result. Eg: 0->00, 1->01,2 ->10,4->100 & 8->1000 when we OR it we don’t loose the bits which corresponds to each value

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s