Enumerations are great things – I use them all the time. Their big advantage is that your code is not littered with magic numbers which, over time, become meaningless as you forget what they represent. And anyone else who needs to modify your code has no idea what they mean.
For example, and these examples are in VB.NET, which is what I am complaining about. Suppose we want to refer to days of the week. We could adopt a convention that each day is numbered:- Sunday =1, Monday = 2, etc. This makes perfect sense until we get code like this:
If DayOfWeek = 3 then
DoSomething
End If
The problem is that we don’t know what “3″ is. If We decided that Sunday was day 1, then 3 would be Tuesday. But if we started our week with Monday then 3 would be Wednesday.
Enumerations to the rescue. To rescue us from all this confusion we create an Enumeration like this:
Public WeekDayEnum
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
End Enum
Then we can change the first bit of code into something more readable:
If DayOfWeek = WeekDayEnum.Tuesday then
DoSomething
End If
So far, so good. And that is how enumerations are generally used. They don’t, of course, have to be public, it depends upon where you declare them. I often stick them in a ProjectEnums file and declare them Public, but you may have an enumeration that relates purely to one class and declare it to be private. Enums are, by default, of type Integer, or, in reality, System.Int32. But you can declare them as other integral type, except Char. You can also declare each item in an enumeration to be a certain value which is useful if you wish to treat your enum as a flag.
But now comes the tricky part. The following example is taken, with a little editing, from the Visual Studio help file. Suppose I want to iterate through the enumeration and check if a certain day has been selected
For Each s as String in [Enum].GetNames(GetType(WeekDayEnum))
If SelectedItem = s then
SelectedValue = _
Ctype([Enum].Parse(GetType(WeekDayEnum),s),WeekDayEnum)
End If
Next
This is crazy syntax! Unless I am missing something. There must be a simpler way to do this. All I want to do is check that if the string s = “Monday” then the SelectedValue will be 1. It can’t be this hard.