Passing bitwise OR enum values

Everyone who has ever used a Regex knows this form of parameter:

[csharp] Regex r = new Regex("", RegexOptions.Singleline | RegexOptions.IgnoreCase); [/csharp]

I often wondered how to do that as well and because nobody ever taught me that at school, I had to figure it out myself. And today I did, and I'm sharing :)

This is very useful if you have a class that takes a lot of options and you don't want to add a bool for each possible option.

First you need to create an enum with the possible options, and number them binary. (eg: 1, 2, 4, 8, 16, ...)

[csharp] public enum Pars { One = 1, Two = 2, Three = 4, Four = 8, Five = 16, Six = 32, Seven = 64 } / Pars / [/csharp]

Next you need to have a method which takes this enum as a parameter, after which you can extract each of the possible options from it with a bitwise AND:

[csharp] private static void TestPars(Pars options) { if ((options & Pars.One) == Pars.One) { Console.WriteLine("One"); } if ((options & Pars.Two) == Pars.Two) { Console.WriteLine("Two"); } if ((options & Pars.Three) == Pars.Three) { Console.WriteLine("Three"); } if ((options & Pars.Four) == Pars.Four) { Console.WriteLine("Four"); } if ((options & Pars.Five) == Pars.Five) { Console.WriteLine("Five"); } if ((options & Pars.Six) == Pars.Six) { Console.WriteLine("Six"); } if ((options & Pars.Seven) == Pars.Seven) { Console.WriteLine("Seven"); } } / TestPars / [/csharp]

When all this is done, you call the method, passing the options you want with a bitwise OR between them, like this:

[csharp] static void Main(string[] args) { TestPars(Pars.Three | Pars.Five | Pars.Seven); } [/csharp]

This example will print Three, Five and Seven.

How does it work internally?

Here are the rules for the bitwise operators:

Bitwise OR: 0101 (expression1)

1100 (expression2)

1101 (result)

Bitwise AND: 0101 (expression1)

1100 (expression2)

0100 (result)

Now, our enum has the following binary values:

1 - 0001 2 - 0010 3 - 0100 4 - 1000 ...

If for example we pass the options One and Two along, we combine them with the bitwise OR, creating 0011.

And if we want to check if Four was passed along, in our if we check if the options combined bitwise with Four result in Four.




Four was not passed.

If we check with Two we get the following:




And 0010 = Two, our if = true, and Two was passed along.

A lot of you will say "well duh, that's basics". Could be true, but I never learned it at school, and never ever had the need for it, but now I wanted to know, and I guess there are more people out there who haven't learned it either.