Enums: Learn to love them

So, I was dredging around in a some old code I inherited looking for that one magical place to make my new change when I came across a piece of code that, well, just made me laugh and then cry.

Here it is:

 1: switch (ddlRollupInterval.SelectedValue) 
 2: { 
 3:     case "Daily": 
 4:         r.RollupInterval = Report.Interval.Daily; 
 5:         break; 
 6:     case "Weekly": 
 7:         r.RollupInterval = Report.Interval.Weekly; 
 8:         break; 
 9:     case "Monthly": 
 10:         r.RollupInterval = Report.Interval.Monthly; 
 11:         break; 
 12:     default: 
 13:         r.RollupInterval = Report.Interval.Yearly; 
 14:         break; 
 15: } 

Looking at the code it is very obvious what it is doing, it is setting an enum value based on the string value of a dropdown.  But did it really take that much code to do it.  Well of course not. 

An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. For example, assume that you have to define a variable whose value will represent a report interval. There are only 4 meaningful values which that variable will ever store. To define those values, you can use an enumeration type, which is declared by using the enum keyword.

 1: enum ReportInterval
 2: {
 3:     Daily,
 4:     Weekly,
 5:     Monthly,
 6:     Yearly
 7: }
The above enum was declared and then an instance was used on the Report object.
 
Enums are extremely flexible and can be used in a number of ways.  Lets look at a few ways you can use enums.
 

Get the Names from the Enum

Lets take the ReportInteval enum we created above and look how we would get an Array of strings that represent the names of each valid enum.

 1: var enumNames = Enum.GetNames(typeof (ReportInterval));

This would allow us to populate that ddlRollupInterval dropdown with all the possible values from the enum

 1: ddlRollupInterval.DataSource = Enum.GetNames(typeof (ReportInterval));
 2: ddlRollupInterval.DataBind();

Ok, so now we have a dropdown filled with the names from the enum, how do we clean up that code we found.  You remember that ugly switch statement that started this whole thing. Once a user selects something in the dropdown and clicks save we want to set the enum based on the string that was selected right? Lets look at how to do that next.

Likewise you can also get the values with the following code:

 1: Array enumValues = Enum.GetValues(typeof(ReportInterval));

Get an Enum from a String

This too is much easier than one would think.  Using the Enum.Parse() method provides a quick way to convert from a string to an instance of the desired Enum.

 1: ReportInterval interval = (ReportInterval)Enum.Parse(typeof(ReportInterval), testString);

This works great in our case because we filled the dropdown with only valid values.  But what if you weren’t sure if the value was valid for the enum or not.  You know those pesky users sometimes give us data that doesn’t fit our model.  ;-)  You can use the Enum.IsDefined() which returns an indication letting us know if a constant with the specified value exists in a specified enumeration.

If our user was able to add a value, say ‘Quarterly’ to our dropdown by some other part of the application and then selected it we would want to test the string we were provided to make sure we don’t throw an unwanted exception.

 1: var ourUserInputString = "Quarterly"
 2:  
 3: if (Enum.IsDefined(typeof (ReportInterval), outUserInputString)
 4: {
 5:     // It is ok go ahead and pase the enum
 6: }
 7: else
 8: {
 9:     // Alert the user an invalid string was selected.
 10: }

Get an Enum from an Integer

Getting an enum instance form an integer is even easier just cast the integer to the desired Enum.

 1: ReportInterval interval = (ReportInterval) testInt;

Of course we would never let our users add values to the dropdown because we want to constrain the valid values to be one that is on the enum, but I wanted to show you that it can be done.

Limit Method Call Arguments

Another usage for an enum is to limit the values a developer can pass to a method on your object.  Using our ReportInterval enum as an argument to a LoadReport method on our Report call gives us the safety net to know we are only going to get a valid value.  Where as if we just used a string we could get a value that doesn’t make sense.

 1: var status = RunReport(ReportInterval.Daily);

Another great part of this is a that Visual Studio will start complaining that the value is in valid unless it is from the enum, further more the compiler will  an argument '1': cannot convert from 'string' to 'EnumTest.ReportInterval'  exception.  I don’t know about your but I like that.

Summary

So what was the final result of fixing the code smell you say?  I replaced that huge 15 line switch statement with the two lines of code, one to verify that the value was correct, remember this is a very, very legacy application and I can not trust that the values were actually loaded to the dropdown from the enum, and one to set the ReportInterval if it checked out good.

I hope that this has shown you just a few ways that the simple Enum can enhance you programming life.

References:

C# Programming Guide: Enumeration Types

How Do Your Convert a String Into an Enum? – Tim Sneath

UGR Episode 4: Interview with Rob Zelt President INETA North America

UGRLogoEpisode 4 of User Group Radio has been released.  While at the MVP Summit in February I got the chance to set down with Rob Zelt the President of INETA North America.  Rob talks about INETA’s mission, programs, and offers information for User Group Leaders on how they can benefit from being an INETA User Group.

This was a fun interview and Rob talked at length about the role of INETA and how it impacts community.

You can listen to the full episode on the User Group Radio site or subscribe to the feed in your favorite podcatcher.

Community Camp Northwest Arkansas May 8th, 2010 in Springdale, AR

image

[UPDATE] This event was canceled to be rescheduled at a later date.  Poor planning on my part since I picked the day before Mother’s Day to hold an event.  What was I thinking?  I am looking for new dates and will post when it is set.

I am happy to announce Community Camp Northwest Arkansas to be held May 8th, 2010 in Springdale, AR.  I am currently working on the website and taking suggestions on topics. 

I want the attendees to build the schedule so if you are planning attending and have a topic you would like to learn or share please email me at jay@jaysmith.us.  I plan to be sending out a session survey to let the registered attendees vote on what sessions out of the proposed they would like to have at the event.  This way you have complete control over what is discussed at the event and will allow you to maximize your time.  If we still have open slots the day of the event we will fill them during the open session.

I am also looking for sponsors for the event, if you are interested in sponsoring Community Camp Northwest Arkansas or future Community Camps in other areas please contact me directly.

I am also working on getting a keynote speaker for the event who can speak about trends and best practices for community.

What is a Community Camp?

A Community Camp is a one day free event for community leader by community leaders based a modified version of Open Space Technology.  This one day free event is intended to be open forum to share ideas, discuss common challenges, and gain from the experience of other leaders.  Community Camps are the perfect opportunity to meet leaders from other groups, benefit from their success stories, and expand your network of contacts.

Who Should Attend?

This event is open to anyone who is a user group leader, or are involved in the leadership, planning, promotion, or day-to-day operations of a user group community.

When is it?

May 8th, 2010

Where is it?

Tyson Corporate Headquarters
2210 West Oaklawn Drive
Springdale, AR 72762

Where do I register?

I have setup an EventBrite registration to track attendees you can register here http://ccnwa2010.eventbrite.com.

Nwa VS2010 Installfest and Board Game Geekout

Devlin Liles on his blog just announced the Visual Studio 2010 Installfest and Board Game Geekout for April 17, 2010.   This is going to be an awesome day spent talking about Visual Studio 2010 and playing games.  Plans are in place for Xbox, PS3, Wii, Settlers of Catan and D&D games to be enjoyed by all attendees.

This a free event happening in Springdale,  AR.  You can register for the event here http://vs2010installfest.eventbrite.com/.

VS2010Installfest

I’ll be there, hope you will be as well.

Please register at http://vs2010installfest.eventbrite.com/

A Funny Thing Happened on the Way to the Olympics

This last week I was privileged to be invited to the MVP Summit in Washington, a grand pilgrimage to the motherland of .NET Developers. A few of my friends who where also going to be there and myself decided to stay an extra day and go to Vancouver B.C. Canada for the Olympics.  I will probably never be this close to the Olympics in my lifetime.

We decided to meet early and rent a car for the drive, since we all flew to the Summit.  We had to leave our hotel get to Avis which was at a nearby hotel.  Our cab driver didn’t know where he was.  If we hadn’t got our iPhones out and used the map app I am certain we would have never arrived.  The kicker is that the nearby hotel was less than a mile way and the driver didn’t know where it was.  Beginning of a great day right, well, keep reading.

So, we finally get to the Avis car rental location and they said we could have any care we wanted as long as it was a Toyota Camry (jQuery15204971249509339897_1360686048207?). Or we could have an Ford F-150 pick-up.  The counter worker seemed to think we would be more comfortable in a Ford.   Not sure if she thought this because we were from Arkansas and Tennessee or not,  put for the 45 minutes we were there she asked us no less than 20 times, “You sure you don’t want the F-150?”. 

Starting to sound like a great day huh?  Well it gets better keep reading.

So, we are finally on the road, both of the passengers, myself included, get car sick so I opted to ride in the back center so I could see out and not get sick.  Remember this fact it will come up again later.  The front seat passenger takes the role of navigator and gets us on our way to Vancouver.  Woo Hoo, this is going to be fun.

About an hour into the drive we top a hill, and see two motorcycle police, one has a car pulled over, the other is staring right at us.  He got on his motorcycle faster than anyone I have ever seen.  He should ride professionally, no seriously I think he made a jump like a jack rabbit being chased by a fox and was moving. We assumed he was coming for us, event though we weren’t sure what the speed limit was.  So, yes we get pulled over, he ask for the drivers license, ask where he is from and then asked the driver to roll down the rear window.  I am thinking, wow this really a friendly officer, he wants to make sure I am ok as well.  He ask where I am from, and ask if I have a seatbelt on, I say no.  He them promptly asked for my license and goes back to his motorcycle.  At this point I am thinking, ok, so maybe he isn’t so nice after all, but hey we are all from other states, in rental car surely he will come back give us a warning, explain things to us and send us on our way.  Oh, no he promptly comes back hands the driver a ticket and me one too.  WHAT, Evidently in Washington State, everyone in the car is required to be wearing a seatbelt.  While all this was going on the other motorcycle officer pulls another car over about 100 feet in front of us.  These guys were out to make their quota. Their buddies in regular cars were doing the same thing about a mile up the road.  This trip is starting to get expensive, $120 for not wearing a seatbelt.

We are finally back on our way and excited to see the Canadian border coming up soon.  Little did we know what extra fun this had waiting for us.  We pull up to the windows, hand over out passports and proceed to answer the 5 million questions that are evidently extremely important to securing Canada from geeks.  How much money do you have, where are going, where are you from, have you been here before, etc. For two of us it was our first time to enter Canada which of course meant that we needed to be detained and further investigation was required.  Another lesson to add to the learning: border crossing officers to not like sarcasm and don’t have a sense of humor.  After about 20 minutes we were given the ok to continue our trip.  Which was a very short time considering the other group had been there for like 3 hours.

About 5 minutes after we crossed into Canada we all got text messages from AT&T telling us that we were going to be charged an additional  $14.95 a day for data unless we turned the data roaming off.  Well now we were screwed since we were using the iPhone Map app to navigate.  Somehow we did manage to make it to Vancouver and I must say that it was a beautiful drive.  The flatness of the valley a stark contrast the the mountains off in the distance like a majestic grandfather watching over his family.

Welcome to Vancouver, not what.  Now GPS, no map, and hungry.  We decided to follow the signs that pointed to the Vancouver Visitor and Information Center.  We never found it because we drove right into the middle of a very large crowd enjoying the Olympic Experience.  We made it, but still didn’t know where we needed to go. First things first, we needed food.  We found a really nice restaurant that was street side where I had an awesome lasagna.  

With full bellies, we set out to see if we could score any tickets.  Oh, and we finally got a map at one of the local hotels.  After walking around for about 2 hours we were able to find some tickets to the Czech Republic and Latvia.  After haggling on the price for a while we finally got the tickets for $120 each. 

The game was awesome, this was my first trip to Canada, to get a ticket while not driving, to be detained at the border, to be at the Olympics, and to see a hockey game.  I must say that the experience was well worth it and I would do it all over again if the opportunity was to arise.  The loved watching hockey and appreciate that a person seated behind us was explaining the game to their guest.  That was great for me cause I didn’t know anything about hockey.  The Czech Republic won the game, but I must say that the Latvia fans were there in full force.

After all that the drive home turned out to be completely uneventful, the experience was awesome and I am glad that I shared it with Randy Walker, and John Kellar and I am sure we will be talking about this for a long time.

Calendar

<<  April 2024  >>
MonTueWedThuFriSatSun
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

View posts in large calendar

Widget Category list not found.

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))X

Tag cloud

    Widget Month List not found.

    Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))X

    Widget AuthorList not found.

    Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))X

    Widget TextBox not found.

    Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))X