Enums and flags maximizing bitwise operations

In C#, enums are a convenient way to define a set of named constants. But did you know that by combining enums with the [Flags] attribute, you can leverage bitwise operations to represent multiple values in a single variable.

Here you can easily append enums using | as for the test example. & operator to check if the enum is present , lastly using ^ for removal. No need to write that complicated for loop to enumerate our enums. just make sure to assign powers of two to each enum value to prevent overlapping bits.

Also a bonus is to use the .HasFlag of the system namespace to check if your enum is present.

This both returns true if the DoorStatus.Open is present on the test enumeration. Same purpose but .HasFlag is more elegant.

0
Subscribe to my newsletter

Read articles from Juan Miguel Nieto directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Juan Miguel Nieto
Juan Miguel Nieto

A software developer trying to write organic blogs.