NET type system is composed of classes, structures, enumerations,
interfaces, and delegates. To begin our exploration of these types, let’s check out the role of the
enumeration (or simply, enums) using a new Console Application project named FunWithEnums.
When building a system, it is often convenient to create a set of symbolic names that map to
known numerical values. For example, if you are creating a payroll system, you may want to refer
to the type of employees using constants such as vice president, manager, contractor, and grunt.
C# supports the notion of custom enumerations for this very reason. For example, here is an
enumeration named EmpType:
// A custom enumeration.
enum EmpType
{
Manager, // = 0
Grunt, // = 1
Contractor, // = 2
VicePresident // = 3
}
The EmpType enumeration defines four named constants, corresponding to discrete numerical
values. By default, the first element is set to the value zero (0), followed by an n+1 progression. You
are free to change the initial value as you see fit. For example, if it made sense to number the members
of EmpType as 102 through 105, you could do so as follows:
// Begin with 102.
enum EmpType
{
Manager = 102,
Grunt, // = 103
Contractor, // = 104
VicePresident // = 105
}
Enumerations do not necessarily need to follow a sequential ordering, and need not have
unique values. If (for some reason or another) it makes sense to establish your EmpType as shown
here, the compiler continues to be happy:
// Elements of an enumeration need not be sequential!
enum EmpType
{
Manager = 10,
Grunt = 1,
Contractor = 100,
VicePresident = 9
}
Thursday, October 22, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment