Advanced C# – Enumeration Types as Bit Flags

Hi guys, it have been a while since my latest post. Today I want to show you a really useful way to use Enumerations in C#. I know everyone knows how and what for use Enums. For instance the most common use for enumerations is to define a list of types. Anyway lets take a few seconds to remind the basics of enumerations in C#.

enum Days 
{ 
	Sunday, 
	Monday, 
	Tuesday, 
	Wednesday, 
	Thursday, 
	Friday, 
	Saturday 
};
enum Months : byte 
{ 
	Jan, 
	Feb, 
	Mar, 
	Apr, 
	May, 
	Jun, 
	Jul, 
	Aug, 
	Sep, 
	Oct, 
	Nov, 
	Dec 
}; 

By default every item in the enumeration is represented by an Integer value (int) but in case you want using a colon you can specify the numeric data type as I did in the example above. The approved types for an enumeration in C# are byte, sbyte, short, ushort, int, uint, long, or ulong.

Days today = Days.Monday;
int dayNumber =(int)today;
Console.WriteLine("{0} is day number #{1}.", today, dayNumber);
//output: Monday is day number #1

We can use either the numeric value of the enumeration or the label value as string so it gives us the possibility to define types and use it along our solution.

Enumerations as bit flags.

One property of the enumerations in C# it’s the possibility of use them as bit flag. It means that you can store in a Enum property several values using the logical operations like AND, OR or XOR as I show you in the following example.

//Adding Tuesday, Thursday and Friday as flag using bitwise OR.
Days meeting = Days.Tuesday | Days.Thursday | Days.Friday;

//test if Thursday is a flag using bitwise AND.
bool test = (meeting & Days.Thursday) == Days.Thursday;
Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not");
//output: Thursday is a meeeting day.

// Remove a flag using bitwise XOR.
meeting = meeting ^ Days.Tuesday;
Console.WriteLine("Meeting days are {0}", meeting);
//output: Meeting days are Thursday, Friday

As you can see we can easily add a flag using OR statement or remove a flag using XOR. In the same way we can validate if a flag is present just using AND. Really easy to use an useful tool.

Just an interesting point the Enum class has a method call HasFlag which receive an Enum value and determines whether one or more bit fields are set in the current instance.

Hope you have enjoyed this post. If you have any question or doubts please do not hesitate to let me know. Otherwise see you online.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s