Game Development Reference
In-Depth Information
instead of numeric values, the type contains words describing different states. In the
case of the
ButtonState
type, these states are
Pressed
and
Released
, because a button
is either pressed or released. Enumerated types are quite handy for representing a
variable that can contain a few different meaningful states. For example, we might
want to store the type of character that a player represents by using an enumerated
type. We can decide ourselves what kind of different states there are in our type, so
before we can use the enumerated type, we first have to define it:
enum
CharacterClan { Warrior, Wizard, Elf, Spy };
The
enum
keyword indicates that we are going to define an enumerated type. After
that follows the name of this type and, between braces, the different states that can
be stored inside a variable of this type. This is the syntax diagram describing the
enum
type definition
:
The type definition can be placed inside a method, but you may also define it
at the class body level, so that all the methods in the class can use the type. You
may even define it as a top-level declaration (outside of the class body). Here is an
example of using the
CharacterClan
enumerated type:
CharacterClan myClan = CharacterClan.Warrior;
In this case, we have created a variable of type
CharacterClan
, which may contain
one of four values:
CharacterClan.Warrior
,
CharacterClan.Wizard
,
CharacterClan.Elf
,or
CharacterClan.Spy
. In a very similar way, the
ButtonState
type is defined somewhere
in a library probably looking something like
enum
ButtonState { Pressed, Released };
Another example of using enumerated types would be to define a type for indicating
the days in the week or the months in a year:
enum
MonthType { January, February, March, April, May, June, July, August,
September, October, November, December };
enum
DayType { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
MonthType currentMonth = MonthType.February;
DayType today = DayType.Tuesday;