Chapter 17. Using Enumerations and Structures
The data types you've learned about so far hold strings, integers, dates, and other predefined kinds of information, but sometimes it would be nice to define your own data types. You might like to be able to make a data type that can hold only certain values, such as a MealType
data type that can hold the values Breakfast, Lunch
, and Dinner
. You might also like to define a type to hold related pieces of data (such as name, address, and phone number) in a single variable.
Enumerations and structures enable you to do these things. An enumeration (or enumerated type) enables you to define a new data type that can take only one of an allowed list of values. A structure enables you to define a group of related pieces of data that should be kept together.
In this lesson, you learn how to define and use enumerations and structures to make your code easier to understand and debug.
ENUMERATIONS
An enumeration is simply a data type that allows only specific values. The following code defines a ContactMethod
enumeration that can hold the values None, Email, Phone
, or SnailMail
:
' Define possible contact methods. Private Enum ContactMethod As Integer None = 0 Email Phone SnailMail End Enum
Internally, an enumeration is stored as an integral data type, by default an Integer
. A number after a value tells Visual Basic explicitly which integer to assign to that value. In the preceding code, None
is explicitly assigned the value 0
.
If you don't specify a value ...
Get Stephens' Visual Basic® Programming 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.