Enum questions

ARC

Well-known member
Joined
Sep 9, 2006
Messages
63
Location
Minnesota
Programming Experience
Beginner
I've looked around, and im still having a little trouble wrapping my head around the use of Enums.

Enums give a textual name to a variable? or does it have to be a constant?

And then what's actually being recovered? the text you labeled the variable with? or the actual integer of the variable? Or are they all automatically number 0 through x where x is the amount of textual representations in the Enum?

Suppose I wanted to grab a random textual representation of a variable inside the Enum below:

VB.NET:
Enum Mood

Angry
Happy
Sad
Confused

End Enum


Private sub Form1_Load...

Dim r As New Random

'obviously this is wrong... but you can see what im asking to do.
me.label1.text =  "You sure are in a " + Me.Mood((r.next(1,4))) + "mood..."

End Sub

Thanks for the help!
 
The point of an Enum is two-fold.

Firstly, it provides a user-friendly label for the developer to use rather than using just raw numbers. If you had to remember what the numbers 0, 1, 2 and 3 meant in your code you'd have to have lots and lots of comments, where remembering what the values Angry, Happy, Sad and Confused is very easy. Under the hood the system uses the numerical values for efficiency, but in your code you use the text labels, which is much more readable.

Secondly, an Enum restricts a variable to only specific values. If you were to use a variable of type Integer then it could have any integer value, not just 0, 1, 2 or 3. If you were to use a variable of type String then it could have any string value, not just "Angry", "Happy", "Sad" or "Confused". By using a variable of the enumerated type you restrict it's possible values to only those four meaningful values. The compiler will not accept anything else.

If you wanted to pick a random enumerated value then you could do this:
VB.NET:
Dim values As Array = [Enum].GetValues(GetType(Mood))
Dim moods As Mood() = DirectCast(values, Mood())
Dim r As New Random
Dim index As Integer = r.Next(0, moods.Length)
Dim mood As Mood = moods(index)

MessageBox.Show(String.Format("You are in a {0} mood.", mood))
 
Back
Top