Lesson 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.

An enumeration (or enumerated type) lets you define a new data type that can take only one of an allowed list of values. For example, a menu program might define a MealType data type that can hold the values Breakfast, Lunch, and Dinner.

The data types described in previous lessons also can hold only a single piece of data: a name, street address, city, or whatever. Sometimes it would be nice to keep related pieces of data together. Instead of storing a name, address, and city in separate strings, you might like to store them as a single unit.

A structure (sometimes called a struct) lets you 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 write, understand, and debug.

Enumerations

Defining an enumeration is easy. The following code defines a ContactMethod enumeration that can hold the values None, Email, Phone, or SnailMail:

// Define possible contact methods.
enum ContactMethod
{
    None = 0,
    Email,
    Phone,
    SnailMail,
}

Internally an enumeration ...

Get C# 24-Hour Trainer, 2nd Edition 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.