This post originated from an RSS feed registered with .NET Buzz
by David Cumps.
Original Post: Passing bitwise OR enum values
Feed Title: David Cumps
Feed URL: http://weblogs.asp.net/cumpsd/rss?containerid=12
Feed Description: A Student .Net Blog :p
Everyone who has ever used a Regex knows this form of parameter:
1Regex r = new Regex("", RegexOptions.Singleline | RegexOptions.IgnoreCase);
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 usefull 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, ...)
1 public enum Pars {
2 One = 1,
3 Two = 2,
4 Three = 4,
5 Four = 8,
6 Five = 16,
7 Six = 32,
8 Seven = 64,
9 } /* Pars */
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:
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.
0011 0100 ---- 0000
Four was not passed.
If we check with Two we get the following:
0011 0010 ---- 0010
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 learnt 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 learnt it either.