[Edit:] The code was edited to reflect some suggestions in the comments by Lorin Thwaits. Thanks again Lorin!
1: Private Enum Direction
2: Up
3: Down
4: Left
5: Right
6: End Enum
7:
8: 'Desc: Cycle through all of the possible directions and Move in that direction.
9: Private Sub MoveInAllDirections()
10: 'Fill an array of all the possible Directions from the enum
11: Dim aDirections As System.Array = System.Enum.GetValues(GetType(Direction))
12:
13: 'Move through each object in the Direction array
14: For Each aValue As Direction In aDirections
15: 'Move in that direction
16: Call MoveIt(aValue)
17: Next
18: End Sub
19:
20: 'Desc: Move in the specified direction
21: Private Sub MoveIt(ByVal theDirection As Direction)
22: 'Move, Move!
23: End Sub
I've been wanting to figure out how to do this for quite a while and I finally took the time to get a solution. If you've ever needed to traverse through all of the objects in an enum, this is how you do it.
The important line of code here is Line 11. With the "System.Enum.GetValues" you can return all of the values of an enum into an array. Now traversing the enum is as simple as move through all of the objects contained in an array.
With this new technique, I've been able to refactor large blocks of code that called a function one by one for each value in an enum. Basically copy and pasted code with just the enum value being passed in to the function changing. Now, I can just loop through the values and call the function within the loop. So much cleaner and when the enum expands, no new code to write.
Hopefully this helps someone else out as well. I know that now that I have this little trick, I'm busy moving through my code and seeing where else this can be used.