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