Search⌘ K
AI Features

Enumerations

Explore how to create and utilize enumerations in C#, enabling you to represent groups of related constants with type safety. Understand how enumerations improve code clarity and safeguard against invalid values while integrating with methods and control flow structures like switch statements.

C# allows us to create enumerations in addition to primitive data types. An enumeration represents a collection of logically related constants.

Suppose a method needs to accept a day of the week as a parameter. We have several options:

  • We could accept a string value (like "Monday").

  • We could accept an integer that represents the day of the week (like 2).

  • We could use enumerations.

Enumerations definition

We can create an enumeration containing all days of the week to ensure the caller selects a valid, predefined constant.

An enumeration is declared using the enum keyword:

enum WeekDay
{
}
Declaring an empty enumeration
  • Line 1: Uses the enum keyword to define a new type named WeekDay.

We can ...