Brendan Tompkins [MVP]

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Three Simple ways to get the most out of your Enums

Yes. Of course. You've heard it again and again.  Enums are great.  Use them and your code will be more maintainable and you'll get less run-time errors.  Everybody says so.  See Paul's blog post here More on using Enums and designing for performance  But to really get the most from enums in C#, you've gotta have a handle on coverting to and from strings and ints to your enumerated object. I explained this to a co-worker recently, and thought I'd share it here.  Pretty simple stuff, but good to have in your bag o' tricks. 

public enum DayOfWeek {
  Sunday = 0,
  Monday = 1,
  Tuesday = 2,
  Wednesday = 3,
  Thursday = 4,
  Friday = 5,
  Saturday = 6
}

1) Going from int to DayOfWeek

DayOfWeek day = (DayOfWeek)1;  // DayOfWeek.Monday

2) Going from DayOfWeek to int

int i = (int) DayOfWeek.Monday; // Equivalent to 1

3) Going from a String to DayOfWeek

DayOfWeek day = (DayOfWeek) Enum.Parse( typeof(DayOfWeek), “Monday“ ); // DayOfWeek.Monday

-Brendan


Posted 11-21-2003 11:13 AM by Brendan Tompkins
Filed under:

[Advertisement]

Comments

Derek wrote re: Three Simple ways to get the most out of your Enums
on 11-21-2003 8:09 AM
The "String to DayOfWeek" method works great for single words, but if you had an enum called "SingleParent", you probably would want to have the string displayed as "Single Parent", which defeats this method. Also, this is not very localization friendly.

- Derek
Brendan Tompkins wrote re: Three Simple ways to get the most out of your Enums
on 11-21-2003 8:20 AM
I agree, I'll ususally create a static method for getting the display string if I need something more than the enum string values.
Darrell Norton's Blog wrote The Benefits of Assigning a Non-default Value to Enums
on 11-25-2003 4:04 AM

Add a Comment

(required)  
(optional)
(required)  
Remember Me?