• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Enum and flags in c#
 

Enum and flags in c#

on

  • 2,121 views

A nice Description given by the author on how to use Enum and Flags in C# ( can also be used in java)

A nice Description given by the author on how to use Enum and Flags in C# ( can also be used in java)

Statistics

Views

Total Views
2,121
Views on SlideShare
2,121
Embed Views
0

Actions

Likes
1
Downloads
12
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Enum and flags in c# Enum and flags in c# Document Transcript

    • Ending the Great Debate on Enum FlagsBy virusstorm | 4 Jun 2012 | ArticleC#2.0C#3.0.NETDevBeginnerC#4.0This article explains how enumeration and flags work in C#.NET and how to properly usethem.See AlsoMore like thisMore by this authorArticle Browse Code Stats Revisions (4) Alternatives 23 Download demo project - 10.8 KBIntroductionEveryone learns about enumeration when they start developing in C#.NET. It is a verysimply structure that can be used to solve a wide range of problems. One of the best usesfor enumeration is using them as a flag. In the .NET Framework, there is a handy attributeyou specify on your enumeration called Flags and now your enumeration will work as aflag. Or so you thought.The reality is there is work you need to do to make the enumeration to function like a flag. Ihave seen experienced .NET developers get caught up working under the assumptionthat Flags handles everything for you. I personally think the reason for this is due to thedocumentation surrounding enumeration and flags. It seems to me the MSDNdocumentation on enumeration fails to explain how enumeration and flags work whichcauses a misunderstanding at implementation time.In this article, I will explain what an enumeration is, what are flags, and how to makeenumeration operate like a flag.BackgroundA few months ago (from when this article was written), I was trying to recall a technique(which I will go over in this article) for setting up enumeration as flags. So I fired up mytrusty web browser and brought up Google and searched for "enum flags". You get a littleover two million results back and naturally, the first few are MSDN documentation pages. AsI was hunting for the article that had the technique I wanted, I became increasinglyfrustrated with the mixed content and descriptions as to how enumeration and flags work. Igot so frustrated between the authors and the comments people were leaving, I decided toset out and write an end all be all solution to this problem.Also, this is my first article, so be kind when you leave comments and feedback.
    • What is enumeration?Enumeration is basically a list of possible values for a variable. The easiest way to applythem is to think of the days of the week. Typically, Sunday is considered to be the first dayof the week and Saturday as the last day of the week. So if we assign a numerical value tothe days of the week, you get the following: Sunday = 1, Monday = 2, Tuesday = 3,Wednesday = 4, Thursday = 5, Friday = 6, and Saturday = 7. So in our program, we canuse these numerical values for the day of the week as opposed to the string value. Thisremoves issues related with string comparison (case issues, which space, special characters,etc.), and it also allows us to save memory and processing time. I know in todays world,memory usage and CPU usage are not a huge issue versus twenty years ago, but thatdoesnt give us the excuse to be lazy or design poorly.In the C#.NET world, we use the keyword enum to define an enumeration. If we use the dayof the week example from above, we would see something like this: Collapse | Copy Codeenum DayOfTheWeek{ Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4, Thursday = 5, Friday = 6, Saturday = 7,}The MSDN reference describes more ways and styles of defining an enumeration. I wouldsuggest checking out theenum (C# Reference) for more details if you are new toenumeration.What are flags?The idea of flags is to take an enumeration value and allow it hold multiple values. If wecontinue with our days of the week example, think of a scheduling application. You want toset up a meeting for Monday, Wednesday, and Friday. The way we previously defined ourenumeration, we would need seven DayOfTheWeek variables defined or create a listof DayOfTheWeek in order to store the days a meeting could be scheduled.If we change the way we defined our enumeration to support the use of flags, we couldavoid adding seven variables or adding the overhead of a list. This is where life getsconfusing. A lot of people believe that simply adding theFlags attribute to the enumerationwill take care of this. That is not the case. To properly implement an enumeration as a flag,you need to have the values increasing by a power of two. So if we define our enumerationto do this, we would get the following: Collapse | Copy Code[Flags]enum DaysOfTheWeek{ Sunday = 1, Monday = 2,
    • Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64}The Why and the HowSo it is at this point, a lot of people get confused. Let us start off by understanding at abinary level, what is going on.Day of the Week Decimal Value Binary Value Sunday 1 0000001 Monday 2 0000010 Tuesday 4 0000100 Wednesday 8 0001000 Thursday 16 0010000 Friday 32 0100000 Saturday 64 1000000What you see here, at a binary level, is a left shift of bits. This is a critical component toflags and how we work with them.Now let us take a look at how we assign values to them. Consider the following codesnippet: Collapse | Copy CodeDaysOfTheWeek daysOfTheWeek;daysOfTheWeek = DaysOfTheWeek.Monday | DaysOfTheWeek.Wednesday | DaysOfTheWeek.Friday;What we have just done here is assigned Monday, Wednesday, and Friday to thevariable daysOfTheWeek. We did this by using an OR operator. Let us look at the binarylevel again and see what happened.Monday 0 0 0 0 0 1 0 | | | | | | |Wednesday 0 0 0 1 0 0 0 | | | | | | |Friday 0 1 0 0 0 0 0Result 0 1 0 1 0 1 0
    • Take note of the result. Remember that the single pipe, "|", in C# is a logic operator, notconditional. This means at a binary level, we OR each position of the binary values. Booleanlogic tells us in an OR situation the result is true when at least one condition is true;otherwise the result is false. What you should begin to see now is that we are using eachposition of the binary value as a switch or flag to indicate when a day of the week has beenselected.To test to see if our result value has a specific flag set, we would use the following syntax: Collapse | Copy Codeif((daysOfTheWeek & DaysOfTheWeek.Monday) == DaysOfTheWeek.Monday){ // Contains Monday!}else{ // DOES NOT Contain Monday!}Before we did a logical OR to combine the flags to store them into a single variable. Now weuse the logical AND operator, "&", to test for the value. Let us look at the binary level to seewhat happened.daysOfTheWeek 0 1 0 1 0 1 0 & & & & & & &Monday 0 0 0 0 0 1 0Result 0 0 0 0 0 1 0Notice that the result is the same as the value for Monday. So when our if statement isevaluated, it returns true. Sure enough, we added Monday to the enumeration. You areprobably wondering how that happened, so let me explain it.Remember that we are doing a logical AND operation. All of the conditions must be true inorder to return a true. By AND-ing the value for Monday and daysOfTheWeek, weessentially are seeing if the position used for signaling Monday is set to true or not.If daysOfTheWeek contains Monday (and in this case it does), the AND operation willreturn the value for just Monday. We then do a conditional comparison to the value ofMonday. The logic can be applied to any day of the week you wish to check for.If daysOfTheWeek does not contain the day you are looking for, the result will be 0 andyour conditional check will be false.So what does the Flags attribute do?So now that we understand the how and the why, people assume that the Flags attributesets up the values accordingly for you. The actual job of the attribute is for readabilitypurposes when debugging or writing the values to a console or a file. Collapse | Copy Code// Writes the following to the console window: Monday, Wednesday, Friday
    • Console.WriteLine(daysOfTheWeek);A Neat TrickDepending on the size of your enumeration, the exponential increase in values can gettricky to keep track of or calculate in your head. There is a technique in C# that will makethis far more manageable, and it is an old one at that. Collapse | Copy Code[Flags]enum DaysOfTheWeek{ Sunday = 1, Monday = 1 << 1, Tuesday = 1 << 2, Wednesday = 1 << 3, Thursday = 1 << 4, Friday = 1 << 5, Saturday = 1 << 6,}Through the use of bit shifting, we can move the 1 bit sequentially without having to worryabout the actual integer value. From a readability stand point, I prefer this. If you get intothe habit of thinking of flags as a series of bit switches, this allows to see which bit switchyou turned on for a specific value. There is nothing that requires you to do this, but it is aneat trick that I like using which I thought would be worth sharing in this article.For more information on this trick, check out the << Operator (C# Reference) article in theMSDN library.